How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
Three ways:
Enum.GetValues(type)
// Since .NET 1.1, not in Silverlight or .NET Compact Frameworktype.GetEnumValues()
// Only on .NET 4 and abovetype.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null))
// Works everywhereI am not sure why GetEnumValues
was introduced on type instances. It isn't very readable at all for me.
Having a helper class like Enum
is what is most readable and memorable for me:
public static class Enum where T : struct, IComparable, IFormattable, IConvertible
{
public static IEnumerable GetValues()
{
return (T[])Enum.GetValues(typeof(T));
}
public static IEnumerable GetNames()
{
return Enum.GetNames(typeof(T));
}
}
Now you call:
Enum.GetValues();
// Or
Enum.GetValues(typeof(Suit)); // Pretty consistent style
One can also use some sort of caching if performance matters, but I don't expect this to be an issue at all.
public static class Enum where T : struct, IComparable, IFormattable, IConvertible
{
// Lazily loaded
static T[] values;
static string[] names;
public static IEnumerable GetValues()
{
return values ?? (values = (T[])Enum.GetValues(typeof(T)));
}
public static IEnumerable GetNames()
{
return names ?? (names = Enum.GetNames(typeof(T)));
}
}