How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
Some versions of the .NET framework do not support Enum.GetValues
. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:
public Enum[] GetValues(Enum enumeration)
{
FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
Enum[] enumerations = new Enum[fields.Length];
for (var i = 0; i < fields.Length; i++)
enumerations[i] = (Enum) fields[i].GetValue(enumeration);
return enumerations;
}
As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.