Friday, July 29, 2011

How to Iterate Through all Enums from a Class in C#

This took me a good while to figure out. This is specifically for looping through multiple enumerations declared inside of a class. This code would have to be modified slightly in order to loop through all enumerations inside of a namespace. I searched for this code everywhere on the net and I couldn't find it so I wrote it myself.


public void GetAllEnums()
 object enumValue;
 string[] arrEnumNames;

 Type enumType;
 FieldInfo field;
 MemberInfo member;
 //Get all of the members of this class, this includes everything
 MemberInfo[] members = typeof(AllEnumsToTable).GetMembers();

 //Loop through the members.
 //Hard coded to 7 because I can't figure out how to filter just for enums
 //System.RuntimeType isn't allowed to be used for what ever reason
 for (int i = 0; i < members.Length; i++ )
  member = members[i];

  if (member.MemberType == MemberTypes.NestedType)
   enumType = Type.GetType(member.DeclaringType.FullName + "+" + member.Name);

   if (enumType.IsEnum)

    arrEnumNames = enumType.GetEnumNames();

    foreach (string name in arrEnumNames)
     field = enumType.GetField(name);

     enumValue = field.GetRawConstantValue();

     Console.WriteLine("Key {0} Value {1}", name, Convert.ToString(enumValue));