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); } } }}
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);
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.