Partager via


Get Names and Values of Enum Members

Yes, reflection can get this done. Assume we have an Enum type - Colors, the following
code will print the name and value for each member of it.

foreach (FieldInfo fi
in typeof(Colors).GetFields(BindingFlags.Public | BindingFlags.Static))

{

   Console.WriteLine(fi.Name);

   Console.WriteLine(fi.GetValue(null));

}

Note we need to specify BindingFlags.Static explicitly here; Otherwise, both static
and instance fields will get returned, including the special instance field "value__".

In fact, BCL provides more neat (and maybe faster) APIs to achieve this:

string[] names = Enum.GetNames(typeof(Colors));

Colors[] values = (Colors[])Enum.GetValues(typeof(Colors));

If the enum type we are exploring is loaded in
the ReflectionOnly context, calling FieldInfo.GetValue will throw "InvalidOperationException:
Code execution is prohibited in an assembly loaded as ReflectionOnly", since GetValue
tries to create an object of the enum type and return it. Same for Enum.GetValues.

The new API in FieldInfo:

public virtual object GetRawConstantValue();

could be what you need in such scenarios. It will return the value of enum's underlying
integer type. For example, if the underlying type of enum "Colors" is byte,
fi.GetRawConstandValue()
will return a boxed byte.

Comments

  • Anonymous
    February 20, 2006
    Many thanks for this entry - I've been trying to find a way to get reflection to locate the XmlEnum() attribute of an Enum's values and this is the only place I found!

    Now to get the attributes.
  • Anonymous
    February 26, 2006
       
           Reflection in .NET 2.0 ships with a new class MethodBody, which "provides access
       ...