I finally got fed up with Enum.Parse

Published 24 July 09 09:02 AM | MattManela 

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.
Filed under: ,

Comments

# kfarmer said on July 24, 2009 2:09 PM:

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.

# MattManela said on July 24, 2009 10:26 PM:

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

# rajkaimal said on July 27, 2009 1:17 AM:

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 comments are disabled

About MattManela

I am a software developer at Microsoft. My blog is http://blogs.msdn.com/matt
Page view tracker