Can I load Enum based on a string name?

Well, I don't think the name says it right ... but here goes:

I have a class with 40 Enums. 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 that I have a dictionary of strings and values, and each line is the name of the above enumerations:

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

I need to change "aaa" to HooBoo.aaa to look at 0. It might not seem like finding a way to do this, since enum is static. Otherwise, I will have to write a method for each enumeration in order to associate a string with it. I can do it, but thats mucho for writing.

Thanks Cooter

+5
source share
4 answers

You will need to use Reflection to get the base type of the enumeration:

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

, :

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

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

→ enum? .

0
source

Just keep in mind that Enum.Parse is not strongly typed ... I believe this will be a real limitation in your scenario. As you can see from the Ngu example, you will need to output the result.

0
source

All Articles