Reverse Reverse Enum Lookup, or GetName - Jon Galloway

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]
Published Wednesday, June 23, 2004 5:25 PM by Jon Galloway
Filed under:

Comments

# re: Reverse Reverse Enum Lookup, or GetName

Enum.GetName(typeof(Direction),(int)Direction.East) sounds like a long-hand way of writing Direction.East.ToString("G"), or is there something I'm overlooking?

Reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemEnumclassToStringtopic.asp

Wednesday, June 23, 2004 10:37 PM by JosephCooney

# re: Reverse Reverse Enum Lookup, or GetName

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

Thanks!

Thursday, June 24, 2004 1:33 AM by Jon Galloway

# re: Reverse Reverse Enum Lookup, or GetName

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

Friday, June 25, 2004 2:29 AM by JosephCooney

# re: Reverse Reverse Enum Lookup, or GetName

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))

Wednesday, June 30, 2004 1:11 AM by AT

Leave a Comment

(required) 
(required) 
(optional)
(required)