Saturday, August 4, 2018

c# - 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.


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...