Luciano Evaristo Guerche

A brazilian geek interested in .NET technologies

About Me

Reverse Enum Lookup

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 Noah Coad]

Comments

Uwe said:

Just wondered whether the compiler/optimizier would ever remove the name-representations and only store the numbers of the enums, but I guess this will never happen?!
# June 23, 2004 11:10 AM

Noah Coad (C# MVP) said:

The names/identifiers are part of its underlying type so no, the compiler does not remove this information.
# June 23, 2004 12:14 PM

William Bartholomew said:

I noticed when you run FxCop on an assembly that uses this technique it says you should request special permissions.
# June 23, 2004 6:45 PM

Luciano Evaristo Guerche said:

I would like to thank everybody who have commented on this post and apologize for not replying ASAP.
# June 28, 2004 1:34 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)