Skip to content

Ease Parsing enums in C# using generics

Once constant annoyance I’ve had with C# has been parsing a string into an enum.

Original C#:

MyEnum e = (MyEnum) Enum.Parse(typeof(MyEnum), "myvalue");

Using generics let you write a function to help:

public static T ParseEnum<T>(string name) {   
  return (T)Enum.Parse(typeof(T), name); 

So then you can simply* say:

MyEnum e = ParseEnum<MyEnum>("myvalue");

A little nicer, but still annoying.
*: simply for C#


  1. Alex wrote:

    Thanks for idea

    Monday, February 19, 2007 at 2:04 am | Permalink
  2. Rob wrote:

    Hey just came across this snippet.

    Very handy. I’ve made it a little more robust, and turned it into an extension method:

    public static T ParseToEnum(this string name)
    if (false == typeof(T).IsEnum)
    throw new NotSupportedException(typeof(T).Name + ” must be an Enum”);

    if(false == Enum.IsDefined(typeof(T), name))
    throw new ArgumentException(string.Format(“{0} is not defined in type of enum {1}”, name, typeof(T).Name));

    return (T)Enum.Parse(typeof(T), name);

    And some unit tests for it:

    public void ParseToEnum_ValidStringValidEnum_ReturnsSuccess()
    var e = “Success”.ParseToEnum();
    Assert.AreEqual(WebExceptionStatus.Success, e);

    [Test, ExpectedException(“System.NotSupportedException”)]
    public void ParseToEnum_TypeIsNotAnEnum_ThrowsException()
    var e = “Success”.ParseToEnum();

    [Test, ExpectedException(“System.ArgumentException”)]
    public void ParseToEnum_StringNotDefinedInEnum_ThrowsException()
    var e = “ThisDoesNotExist”.ParseToEnum();

    Thursday, March 5, 2009 at 9:42 am | Permalink
  3. Rob Volk wrote:

    The extension method is what I was looking for. Works great. I love open source development via blog comments! thanks guys.

    Thursday, February 18, 2010 at 12:20 pm | Permalink
  4. Rob Volk wrote:

    BTW – you forgot the generic declaration on the method signature. Should be:

    public static T ParseToEnum(this string name)

    Thursday, February 18, 2010 at 12:30 pm | Permalink
  5. ryan wrote:

    @Rob Volk: I bet wordpress is eating the angle brackets

    Thursday, February 18, 2010 at 12:45 pm | Permalink