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))





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,
will return a boxed byte.