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<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:
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.