Using Enum.Parse()

Have you ever written any code along the lines of...

myEnum GetEnumValue(string EnumString)
    myEnum enumValue;
    switch (EnumString)
        case "Value1":
            enumValue = myEnum.Value1;
        case "Value2":
            enumValue = myEnum.Value2;
            enumValue = myEnum.ValueNone;
    return enumValue;

Embarrassingly, I did. Until I realised that the Enum class had a static method called Parse that can be used as follows...

myEnum GetEnumValue(string EnumString)
    return (myEnum)Enum.Parse(typeof(myEnum),EnumString);

Easy! Robust! and all that.

Author Dave Howard

I have been involved in IT development for the last 10 years - a lot of it around desktop applications and telecoms.


Paul said:


20/Jun/2007 11:46 AM

Ben said:

Thanks, I have to look this up every time I need it.

Just one thing, why would you call your Enum "myEnum", even for this example surely it should by "MyEnum"?


08/May/2008 15:52 PM

Add Comment


Your comment has been received and will be shown once it passes moderation.