Avatar
11977 reputation
Posted on:02 Sep '16 - 10:37
200

How do I enumerate an enum?

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 compile time error:
'Suit' is a 'type' but is used like a 'variable'
It fails on the Suit keyword, the second one.

C#

Answers

399
This answer is accepted

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
    // ...
}

Avatar
7718 reputation
Posted on:02 Sep '16 - 11:04

Please login in order to answer a question