Artur
Artur

Reputation:

How to create enum object from its type and name of the value?

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

Answers (3)

Yuval
Yuval

Reputation: 1382

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

You also have a case-insensitive overload.

Upvotes: 16

Brad Patton
Brad Patton

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

Pavel Chuchuva
Pavel Chuchuva

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

Related Questions