How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
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());
}
}