How can you enumerate an enum in C#?
E.g. the following code does not compile:
public enum Suit
{
What if you know the type will be an enum, but you don't know what the exact type is at compile time?
public class EnumHelper
{
public static IEnumerable GetValues()
{
return Enum.GetValues(typeof(T)).Cast();
}
public static IEnumerable getListOfEnum(Type type)
{
MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
return (IEnumerable)getValuesMethod.Invoke(null, null);
}
}
The method getListOfEnum uses reflection to take any enum type and returns an IEnumerable of all enum values.
Usage:
Type myType = someEnumValue.GetType();
IEnumerable resultEnumerable = getListOfEnum(myType);
foreach (var item in resultEnumerable)
{
Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}