Click here to Skip to main content
15,886,024 members
Articles / Programming Languages / C# 4.0
Alternative
Tip/Trick

A Generic enum Parser in C#

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
7 Jun 2011CPOL 12.3K   1   6
The ParseEnum method will not work where we use a version below .NET Framework 4.0 because of the TryParse method. So those who need to use it in below .NET Framework 4.0 or in .NET Framework 4.0, the following extension methods will be helpful:public static TEnum ParseEnum(this...
The ParseEnum method will not work where we use a version below .NET Framework 4.0 because of the TryParse method. So those who need to use it in below .NET Framework 4.0 or in .NET Framework 4.0, the following extension methods will be helpful:

C#
public static TEnum ParseEnum<TEnum>(this string dataToMatch, bool ignorecase = default(bool))
  where TEnum : struct
{
  return dataToMatch.IsItemInEnum<TEnum>()() ? default(TEnum) : 
     (TEnum)Enum.Parse(typeof(TEnum), dataToMatch, ignorecase );
}

public static Func<bool> IsItemInEnum<TEnum>(this string dataToCheck)
   where TEnum : struct
{
   return () => { return string.IsNullOrEmpty(dataToCheck) || !Enum.IsDefined(typeof(TEnum), dataToCheck); };
}

Usage:
C#
object[] items = new object[] { "One".ParseEnum<EnumTwo>(), "Two".ParseEnum<EnumTwo>() };

Note that these extension methods are part of .NET Extensions Methods Library for C# and VB.NET[^] project in the CodePlex.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Australia Australia

Comments and Discussions

 
GeneralRe: Seems it's available from .Net 3.5 (http://msdn.microsoft.co... Pin
Espen Harlinn30-May-11 11:02
professionalEspen Harlinn30-May-11 11:02 
GeneralThanks Kiswa00. Pin
Mohammad A Rahman7-Jun-11 11:21
Mohammad A Rahman7-Jun-11 11:21 
GeneralReason for my vote of 3 See comment on alternate. Pin
kiswa007-Jun-11 2:25
kiswa007-Jun-11 2:25 
GeneralTwo things: One, I think you mean "a version below .NET Fram... Pin
kiswa007-Jun-11 1:58
kiswa007-Jun-11 1:58 
GeneralTryParse is available from at least 2.0 and up. Pin
#realJSOP30-May-11 2:10
mve#realJSOP30-May-11 2:10 
GeneralRe: Sorry it is my mistake, I should mentioned it clearly before... Pin
Mohammad A Rahman30-May-11 2:36
Mohammad A Rahman30-May-11 2:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.