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.
A simple and generic way to convert an enum to something you can interact:
And then:
This question appears in Chapter 10 of "C# Step by Step 2013"
The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):
In this case,
Suit
andValue
are both enumerations:and
PlayingCard
is a card object with a definedSuit
andValue
:Add method
public static IEnumerable<T> GetValues<T>()
to your class, likecall and pass your enum, now you can iterate through it using
foreach
Three ways:
Not sure why was
GetEnumValues
introduced on type instance, it isn't very readable at all for me.Having a helper class like
Enum<T>
is what is most readable and memorable for me:Now you call:
One can also use sort of caching if performance matters, but I don't expect this to be an issue at all
There are two ways to iterate an
Enum
:The first will give you values in form on a array of
object
, and the second will give you values in form of array ofString
.Use it in
foreach
loop as below:I do not hold the opinion this is better, or even good, just stating yet another solution.
If enum values range strictly from 0 to n - 1, a generic alternative:
If enum values are contiguous and you can provide the first and last element of the enum, then:
but that's not strictly enumerating, just looping. The second method is much faster than any other approach though...