Share via


I finally got fed up with Enum.Parse

I don’t know why I didn’t do this long ago, but I am done writing this:

 var val = (SomeEnum)Enum.Parse(typeof(SomeEnum),”someString”);

I have typed this too many times and it annoys me. 

I wrote a small extension method on the string type to make this better:

 public static class StringExtensions
{
    public static T ToEnum<T>(this string @string)
    {
        return (T)Enum.Parse(typeof (T), @string);
    }
}

With this I can now write the previous line as:

 var val = "someString".ToEnum<SomeEnum>()

It is a bit shorter and I think much more readable.

Comments

  • Anonymous
    July 24, 2009
    Yeah, that one's been tossed around before, for good reason. The problem, unfortunately, is that T is unconstrained, and until we can constrain it to enum, the extension isn't as solid as it could be.

  • Anonymous
    July 24, 2009
    Yeah, When writing it I tried to constrain it to enum and was met with a unfriendly error message :)

  • Anonymous
    July 26, 2009
    I did something similar sometime back and ended up semi-constraining it like so: public static T ToEnum<T>(this string enumString) where T : struct

  • Anonymous
    December 31, 2009
    I wouldn't do it as an extension for string. I would rather have it in a tool like: GetEnumValue<T>(string @string); Anyway, good idea tho. Thanks