tags:

views:

1819

answers:

3

I have a type (System.Type) of an enum and a string containing enumeration value to set.

E.g. given:

enum MyEnum { A, B, C };

I have typeof(MyEnum) and "B".

How do I create MyEnum object set to MyEnum.B?

+10  A: 

MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");

You also have a case-insensitive overload.

Yuval
A: 

I assume you don't have access to MyEnum, only to typeof(MyEnum):

void foo(Type t)
{
   Object o = Enum.Parse(t, "B");
}
Pavel Chuchuva
A: 

I created a bunch of wrappers for doing this, as all the casting is a pain is the ass.

CLR Extensions

Jonathan Allen