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 (4)
  1. Keith Farmer says:

    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.

  2. Yeah, When writing it I tried to constrain it to enum and was met with a unfriendly error message 🙂

  3. rajkaimal says:

    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

  4. weitzhandler says:

    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.


Comments are closed.

Skip to main content