snippetcsharpCritical
How to enumerate an enum?
Viewed 0 times
enumenumeratehow
Problem
How can you enumerate an
E.g., the following code does not compile:
And it gives the following compile-time error:
'Suit' is a 'type' but is used like a 'variable'
It fails on the
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.Solution
Update: If you're using .NET 5 or newer, use this solution.
Note: The cast to
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.Code Snippets
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}Context
Stack Overflow Q#105372, score: 5324
Revisions (0)
No revisions yet.