How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
You won't get Enum.GetValues()
in Silverlight.
Original Blog Post by Einar Ingebrigtsen:
public class EnumHelper
{
public static T[] GetValues()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List values = new List();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add((T)value);
}
return values.ToArray();
}
public static object[] GetValues(Type enumType)
{
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List