Wednesday, November 19, 2008

Enum.GetValues in Compact Framework

Sadly, the Compact Framework does not support Enum.GetValues which is a pain if you need to iterate over an enumeration, but it can easily be accomplished using good ol' Reflection:

public IEnumerable<Enum> GetValues(Enum enumeration)
{
List<Enum> enumerations = new List<Enum>();
foreach (FieldInfo fieldInfo in enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
{
enumerations.Add((Enum)fieldInfo.GetValue(enumeration));
}
return enumerations;
}


And you can call the method as such:

foreach (DayOfWeek dayOfWeek in GetValues(new DayOfWeek())) {}

Enjoy!

3 comments:

Thiago said...

Follows a method which do the same as Enum.GetValues() and works in in the compact framework.

public static Array GetEnumValues(Type enumerationType)
{
if (!enumerationType.IsEnum)
throw new InvalidParameterValueException("GetEnumValues(enumerationType)", enumerationType);

object valAux = Activator.CreateInstance(enumerationType);
FieldInfo[] fieldInfoArray = enumerationType.GetFields(BindingFlags.Static | BindingFlags.Public);

Array res = Array.CreateInstance(enumerationType, fieldInfoArray.Length);
for (int i = 0; i < res.Length; i++)
res.SetValue(fieldInfoArray[i].GetValue(valAux), i);
return res;
}

Dale said...

Oops, my first post did not escape the < and > in my snippet, my bad!

Daniel F. said...

Thank you! Totally works for my .NET Compact 3.5 project.