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!










5 comments:
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;
}
Oops, my first post did not escape the < and > in my snippet, my bad!
Thank you! Totally works for my .NET Compact 3.5 project.
Pity it took me an hour of searching to find this post..
Worked perfectly..
Used this site
to convert the code to vb.net (don't hold that against me)... :-)
Thanks for your help...
Public Shared Function GetValues(ByVal enumeration As [Enum]) As IEnumerable(Of [Enum])
Dim result As New List(Of [Enum])()
For Each fieldInfo As FieldInfo In enumeration.GetType().GetFields(BindingFlags.Static Or BindingFlags.Public)
result.Add(DirectCast(fieldInfo.GetValue(enumeration), [Enum]))
Next
Return result
End Function
Post a Comment