tags:

views:

2087

answers:

8

What's the best way to convert a string to an enumeration value in C#?

I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the enumeration value.

In an ideal world, I could do something like this:

StatusEnum MyStatus = StatusEnum.Parse("Active");

but that isn't valid code.

+2  A: 

http://msdn.microsoft.com/en-us/library/aa328348.aspx

You're looking for Enum.Parse.

DavidWhitney
+23  A: 

It's rather ugly:

StatusEnum MyStatus = (StatusEnum) Enum.Parse( typeof(StatusEnum), "Active", true );

I tend to simplify this with:

public static T ParseEnum<T>( string value )
{
    return (T) Enum.Parse( typeof( T ), value, true );
}

Then I can do:

StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
Keith
If performace is important (which always is) chk answer given by Mckenzieg1 below : http://stackoverflow.com/questions/16100/converting-a-string-to-an-enumeration-value-in-c/38711#38711
@avinashr is right about @McKenzieG1's answer, but it isn't ALWAYS important. For instance it would be a pointless micro optimisation to worry about enum parsing if you were making a DB call for each parse.
Keith
A: 

Further example:

SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");

DavidWhitney
A: 

Enum.Parse is your friend:

StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active");
tags2k
A: 
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So if you had an enum named mood it would look like this:

   enum Mood
   {
      Angry,
      Happy,
      Sad
   } 

   // ...
   Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
   Console.WriteLine("My mood is: {0}", m.ToString());
brendan
+1  A: 
// str.ToEnum<EnumType>()
T static ToEnum<T>(this string str) 
 { return (T) Enum.Parse(typeof(T), str);
 }

@keith thanks. I took it out.

Mark Cidade
+1  A: 

@marxidad - it makes sense as a string extension, but that won't work, you can't use Enum as a constraint.

I already asked about it.

Keith
+4  A: 

Note that the performance of Enum.Parse() is awful, because it is implemented via reflection. (The same is true of Enum.ToString, which goes the other way.)

If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a Dictionary<String,YourEnum> at startup and use that to do your conversions.

McKenzieG1