Reverse Reverse Enum Lookup, or GetName

Noah posts about how to look up an enum to a string. If you've got an enum and you want the value as a string, you'd use Enum.GetName , as in:
Enum.GetName(typeof(Direction),(int)Direction.East)

GetNames returns a string array of Enum values, which is also useful.

Sometimes you may have the string name of an enumeration identifier, and want its enum type. For example, you write a enum identifier as a string to a file and want to read it back and obtain the original enumeration type. This takes place when you serialize a class to an XML file and deserialize it back using XmlSerializer.

private enum Direction {North, South, East, West}; private Direction ParseDirection(string name) { return (Direction) Enum.Parse(typeof(Direction), name, true); }

[Via Coad's Code Block]

3 Comments

  • Nope, you're not overlooking a thing. I get paid by the character.



    Thanks!

  • Hmmm....I don't :-)

  • I've little helper class thich allow to make my code readble and strongly-typed using generics:



    static class Enums<T> {

    static T Parse(String s);

    static T Parse(String s, bool caseInsens);

    static bool TryParse(int i, out T result);

    static bool TryParse(String s, out T result);

    static String ToString(T e);

    }



    This way you can use

    Enums<Direction>.Parse(name, true);

    without possible problems with cast to/out of object ;o))

Comments have been disabled for this content.