Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 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 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.

like image 716
Ian Boyd Avatar asked Sep 19 '08 20:09

Ian Boyd


People also ask

How do you declare an enumeration?

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.

How do I display the value of an enum?

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.


2 Answers

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.

like image 150
jop Avatar answered Sep 21 '22 06:09

jop


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());     } } 
like image 35
Haacked Avatar answered Sep 24 '22 06:09

Haacked