Apr 2, 2014

How to Convert a string to an enum in C#?

It's rather ugly:

SampleEnum myEnum = (SampleEnum) Enum.Parse( typeof(SampleEnum), "Active", true);

I tend to simplify this with:
public static T ParseEnum<T>( string value )
{
    return (T) Enum.Parse( typeof( T ), value, true );
}
Then I can do:
SampleEnum myEnum = EnumUtil.ParseEnum<SampleEnum>("Active");

No comments: