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#

2 Comments »

  1. Alex said,

    February 19, 2007 @ 2:04 am

    Thanks for idea

  2. low airfares said,

    March 15, 2008 @ 2:21 am

    low airfares

    http://topairline.freehostpage.com/low-airfares low airfares

RSS feed for comments on this post · TrackBack URI

Leave a Comment