Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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.
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in