65.9K
CodeProject is changing. Read more.
Home

A Generic enum Parser in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

May 19, 2011

CPOL
viewsIcon

17432

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 strings:
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>();