How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
And gives the following compile-time error:
'Suit' is a 'type' but is used like a 'variable'
It fails on the Suit
keyword, the second one.
I think this is more efficient than other suggestions because
GetValues()
is not called each time you have a loop. It is also more concise. And you get a compile-time error not a runtime exception ifSuit
is not anenum
.EnumLoop
has this completely generic definition:I know it is a bit messy but if you are fan of one-liners, here is one:
Also you can bind to the public static members of the enum directly by using reflection:
It looks to me like you really want to print out the names of each enum, rather than the values. In which case
Enum.GetNames()
seems to be the right approach.By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.
I would use
Enum.GetValues(typeof(Suit))
instead.(The current accepted answer has a cast that I don't think is needed (although I may be wrong).)