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#

5 Comments »

  1. Alex said,

    February 19, 2007 @ 2:04 am

    Thanks for idea

  2. Rob said,

    March 5, 2009 @ 9:42 am

    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:

    [Test]
    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();
    }

  3. Rob Volk said,

    February 18, 2010 @ 12:20 pm

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

  4. Rob Volk said,

    February 18, 2010 @ 12:30 pm

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

    public static T ParseToEnum(this string name)

  5. ryan said,

    February 18, 2010 @ 12:45 pm

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

RSS feed for comments on this post · TrackBack URI

Leave a Comment