Author Topic: C# Reflection - How to enumerate the name and value with enums?  (Read 3708 times)

administrator

  • Administrator
  • Full Member
  • *****
  • Posts: 69
The following code would load the C# assembly at run time with System.Reflection.Assembly.LoadFile(filename) . If you want to enumerate the list of names and values defined as given below:

enum eMonths
{
     mJan = 1, mFeb = 2, mMar = 3, mApr = 4, ...., mDec = 12
};


The name of enumeration "eMonths" would be given as string parameter to assembly.GetType("eMonths"); With its return type, you can make a call to GetFields() that returns  FieldInfo[] array. Iterating through the array elements, you will get the name and value.

Code: (C#)
//Source Code Listing

         Assembly assembly = Assembly.LoadFile("c:\\testserver.dll");
         Type enumType = assembly.GetType("eMonths");         

         foreach(FieldInfo fi in enumType.GetFields())
         {
            if (fi.FieldType.BaseType.Name == "Enum")
            {
               string name = fi.Name;
               int value = (int)fi.GetRawConstantValue();
               System.Console.Write(name + "-" + value.ToString());
            }
         }

The above code would produce the following output:

mJan - 1
mFeb - 2
mMar - 3
mApr - 4
- - -
- - -
mDec = 12

« Last Edit: December 01, 2011, 06:08:45 pm by kathir »

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1