First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

This might seems a pretty trivial problem, but every time I've to get an Enum given its name I forgot how to do it, and I've to look for it on Google.

So, is there a better way to remember something you always forget than writing a post about it?

Back to the problem: going from an Enum to its numeric value or its string representation is quite easy:

/* Enum to string */
string stringValue = enumVal.ToString();

/* Enum to numeric value */
int numericVal = (int) enumVal;

And going from a numeric value to the Enum is quite as easy:

/* Numeric value to Enum
int numericVal = 3;
MyEnum enumVal = (MyEnum) numericVal;

But going from the name to the Enum is a bit more complicate... well, if you don't remember the function call: the System.Enum class has a static method (Enum.Parse) that converts a string to the Enumerated type specified:

/* String to Enum */
MyEnum enumVal = (MyEnum) Enum.Parse(typeof(MyEnum), stringValue);

Too bad the need for the cast: they could have implemented a generic version of the Parse method.

I hope I'll remember this function call next time I need it... or at least I know where to look for it.

Technorati tags: , ,
posted on Tuesday, September 25, 2007 5:57 PM

Comments on this entry:

# re: String to Enum

Left by Eber Irigoyen at 9/26/2007 2:51 AM

how about this

almost same code, but more intuitive

# re: String to Enum

Left by Simone Chiaretta at 9/26/2007 10:25 AM

Thank you Eber,
that's a great implementation.
The link is:
My new little friend, Enum<T>

# re: String to Enum

Left by Scott at 9/26/2007 4:54 PM

I wrote a follow up post to yours and combined what Scott W. and Kenny had implemented. The difference is that mine can act as an extension method on a string as well as the traditional helper class.

# re: String to Enum

Left by Simone Chiaretta at 9/26/2007 5:00 PM

Hi Scott, yes, I saw it, strange that it has not been added as trackback to the post

Comments have been closed on this topic.