Parsing Strings to Enums with a Simple Univeral Extension

getting an enum to a string is easy, but switching back can be a pain

If I have an enum:
public enum WhatToShow { All, Courses, Seminars };

and I want to turn a string "Courses" back into that enum Type, there are a few ways I could do it. The most basic way would be to use a switch statement; that is a pain, especially for large enums, plus it has to be re-written for each enum. Here is a simple extension you can use to convert strings back into enums:
public static T ToEnum<T>(this string strOfEnum)
    return (T)Enum.Parse(typeof(T), strOfEnum);

Now if I have a simple string, it is simple to turn it back to an enum:
string str = "Courses";
WhatToShow en = str.ToEnum<WhatToShow>();

Comments (3) -

  • I believe your extension is slightly incorrect, should be

    public static T ToEnum<T>(this string str)
                return (T)Enum.Parse(typeof(T), str);
  • You just re-typed the extension and changed the variable name... am I missing something?
  • Ahh, you're right, forgot to replace the brackets in html... browser thought it was an element.

Add comment