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 it 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.
The keyword 'enum' is used to declare new enumeration types in C and C++. Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag.
An enumeration is a great way to define a set of constant values in a single data type. If you want to display an enum's element name on your UI directly by calling its ToString() method, it will be displayed as it has been defined.
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { }
Note: The cast to (Suit[])
is not strictly necessary, but it does make the code 0.5 ns faster.
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.
public enum Suits { Spades, Hearts, Clubs, Diamonds, NumSuits } public void PrintAllSuits() { foreach (string name in Enum.GetNames(typeof(Suits))) { System.Console.WriteLine(name); } }
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.
public enum Suits { Spades, Hearts, Clubs, Diamonds, NumSuits } public void PrintAllSuits() { foreach (var suit in Enum.GetValues(typeof(Suits))) { System.Console.WriteLine(suit.ToString()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With