0

Possible Duplicate:
Cast a String to an Enum Tag in C#

How to convert a string which have a name of existing enum-TAG (have name of Enum Title) to become of type of Enum

Not to become one of the Enum listed variables values,
But to be the Enum-Tag name which is of type Enum?

For instance, I might have

Enum MyEnum { A,B,C,D };

and then

String a = "MyEnum";
Community
  • 1
  • 1
  • 2
    This question seems popular today - what is going on? – Tim Lloyd Jan 24 '11 at 13:58
  • I think you want to turn a simple type-name into a System.Type? This is difficult to do *reliably* without more information available than just the simple name. Do you know the assembly the type is in? Do you have the assembly-qualified name or at least the fully-qualified type name? Anyway, this should get you started: Creating C# Type from full name. http://stackoverflow.com/questions/1392763/creating-c-type-from-full-name – Ani Jan 24 '11 at 14:01
  • This was closed too hastily; I believe the OP wants something different from what is in the "duplicate". – Ani Jan 24 '11 at 14:03

3 Answers3

3

You need to parse it as Enum using Enum.Parse:

myEnum result = (myEnum)Enum.Parse(typeof(myEnum), stringToConvert);

There is a couple of elements to consider here. First of all the Enum.Parse takes the type of the target Enum. Second is it only returns type object so you need to manually convert it to the correct enum type.

Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97
1
MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum), "myname");
Sandor Drieënhuizen
  • 6,310
  • 5
  • 37
  • 80
0
Enum e = (Enum)Enum.Parse(typeof(Enum), "A", true);

this should do it

stack72
  • 8,198
  • 1
  • 31
  • 35