Reputation:
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?
Upvotes: 4
Views: 17061
Reputation: 1382
MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");
You also have a case-insensitive overload.
Upvotes: 16
Reputation: 4205
You can do this with generics. I created a Utility class to wrap this:
public static class Utils {
public static T ParseEnum<T>(string value) {
return (T)Enum.Parse(typeof(T), value, true);
}
Then invoked like:
string s = "B";
MyEnum enumValue = Utils.ParseEnum<MyEnum>(s);
Upvotes: 1
Reputation: 22475
I assume you don't have access to MyEnum, only to typeof(MyEnum):
void foo(Type t)
{
Object o = Enum.Parse(t, "B");
}
Upvotes: 3