MrDave's (David Yack) WebLog

Mission Enum Possible

 

I’m sure you have all been there – thinking “This must be possible” and then the search begins for the answer – you check Google, and all other known sources.    Then just seconds before you give up your quest – you find the answer!

 

Last week I was determined to find a better way to look up the value of an Enum from a string value.  For example I have the following Enum

 

public enum MyEnum

{

            MyValue1 = 1,

            MyValue2 = 2,

            Etc…

};

 

MyEnum eMyEnum;

 

What I wanted to do is take a string containing “MyValue2” and assign it to eMyEnum.

 

After searching Google, my inside c# book and a few other places I was convinced that reflection must have something to do with answer.  While you can retrieve info about the Enum setting the value from a string still was elusive.

 

Finally just before I was about to give up I came across the Enum.Parse method.

 

Using one line of code you can use Enum.Parse method to set the value of your Enum variable.

 

Example

 

eMyEnum = (MyEnum ) Enum.Parse(TypeOf(MyEnum),”Value2”);

 

Ok let’s have a confession of how many case statements you could replace now that you know about Enum.Parse

Comments

Paul Wilson said:

Does it require case-sensitivity? I usually have my case statements check both the input and the cases in upper case to be case insensitive -- and I don't want to lose that, although I do really like Enum.Parse.
# March 6, 2004 1:54 PM

David Yack said:

No - theres another overload that takes a bool saying if you want it to be case sensitive or not.

And I didn't add this in the post - but it can be the Enum Name or Numeric value
# March 6, 2004 2:03 PM

Jason said:

D'oh....

I guess I know what I'm doing on Monday...self code-review... Thanks for the tip!
# March 6, 2004 10:31 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)