Tuesday, January 8, 2019

How do I enumerate an enum in C#?

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 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)))
{
}


No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...