A Generic enum Parser in C#
A possibly simpler version of this is to create an extension method for strings:public static class MyExtensions{ public static TEnum ParseEnum(this string value, bool ignoreCase = false) where TEnum : struct { TEnum tenumResult; ...
A possibly simpler version of this is to create an extension method for
string
s:
public static class MyExtensions
{
public static TEnum ParseEnum<TEnum>(this string value,
bool ignoreCase = false) where TEnum : struct
{
TEnum tenumResult;
Enum.TryParse<TEnum>(value, ignoreCase, out tenumResult);
return tenumResult;
}
}
Note that you also do not need to assign or return default(TEnum)
because Enum.TryParse
will always set tenumResult
for you, regardless of success or failure when parsing.
Usage:
var enumValue = "One".ParseEnum<EnumOne>();