Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

A Generic enum Parser in C#

3.00/5 (1 vote)
7 Jun 2011CPOL 13K  
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)