Aug 16 2009

Enum.GetValues() for Silverlight

I ran into a problem the other day using enums in Silverlight. I needed a way to enumerate all the valid values in an enum. In the standard CLR I would use Enum.GetValues, but it turns out that function isn’t provided in Silverlight. So, I did a little decompiling and found that the standard CLR uses some simple reflection in the guts of GetValues. Armed with that knowledge, I created this helper function.


public static IEnumerable<T> GetEnumValues<T>()
{
  Type type = typeof(T);

  if (!type.IsEnum)
  {
    throw new Exception("{0} is not an enum.", type.FullName);
  }

  FieldInfo[] fields =
      type.GetFields(BindingFlags.Public | BindingFlags.Static);

  foreach (var item in fields)
  {
    yield return (T)item.GetValue(null);
  }
}

Using this function is pretty straight forward. It might look something like this…


foreach (var item in GetEnumValues<MyEnum>())
{
  //do stuff here
}
  • Share/Save/Bookmark