The following application shows a subtle difference in dealing with enums using Enum class methods and when using reflection. In this sample, I am looking to find the number of elements in the enum.
Enum.GetValues and
Enum.GetNames are not implemented in the .NET Compact Framework, so I cannot use those methods.
By using reflection, I figured I would gain the upper hand and take control of my enum woes. Unfortunately, calling GetFields on an enum type adds an extra entry named "value__" to the returned list. After browsing through the decompilation of Enum, I found that value__ is just a special instance field used by the enum to hold the value of the selected member. I also noticed that the actual enum members are really marked as static. So, to get around this problem, all you need to do is call GetFields with the BindingFlags set to only retrieve the public, static fields (see the code example below).
using System;
using System.Reflection;
namespace EnumReflection
{
class Program
{
enum Test
{
One,
Two,
Three
}
static void Main(string[] args)
{
Type enumType = typeof(Test);
//The following prints 3, but we can't use this method in .NET CF
Console.WriteLine(Enum.GetValues(enumType).Length);
FieldInfo[] infos;
infos = enumType.GetFields();
//The following prints 4! There is an extra, unrelated Int32 entry named "value__"
//at the zeroth element of the info array.
Console.WriteLine(infos.Length);
//The following prints the 3 enum elements. The value__ field is removed by
//specifying we only want the public, static fields.
infos = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo fi in infos)
{
Console.WriteLine(fi.Name);
}
}
}
}