Cooter
Cooter

Reputation: 559

Possible to load an Enum based on a string name?

OK, I don't think the title says it right... but here goes:

I have a class with about 40 Enums in it. i.e:

    Class Hoohoo
    {

       public enum aaa : short
       {
          a = 0,
          b = 3
       }

      public enum bbb : short
      {
        a = 0,
        b = 3
      }

      public enum ccc : short
      {
        a = 0,
        b = 3
      }
}

Now say I have a Dictionary of strings and values, and each string is the name of above mentioned enums:

Dictionary<string,short>{"aaa":0,"bbb":3,"ccc":0}

I need to change "aaa" into HooBoo.aaa to look up 0. Can't seem to find a way to do this since the enum is static. Otherwise I'll have to write a method for each enum to tie the string to it. I can do that but thats mucho code to write.

Thanks, Cooter

Upvotes: 5

Views: 1275

Answers (4)

Aaronaught
Aaronaught

Reputation: 122624

You'll have to use Reflection to get the underlying enum type:

Type t = typeof(Hoohoo);
Type enumType = t.GetNestedType("aaa");
string enumName = Enum.GetName(enumType, 0);

If you want to get the actual enum value, you can then use:

var enumValue = Enum.Parse(enumName, enumType);

Upvotes: 4

Michael Ulmann
Michael Ulmann

Reputation: 1087

Just keep in mind that Enum.Parse isn't strongly typed... I reckon that will be a real limitation in your scenario. As you can see from Ngu's example you'd have to cast the output.

Upvotes: 0

Graviton
Graviton

Reputation: 83254

Use

aaa myEnum =(aaa) Enum.Parse(typeof(aaa), "a");

Upvotes: 2

Joel
Joel

Reputation: 16655

You want to convert a string -> enum? This should help.

Upvotes: 0

Related Questions