How to enumerate an enum

0 votes

In C#, how do you enumerate an enum?

For example, the following code fails to compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

The error that I get is related to Suit. What is going on? How to fix it?

Jun 11 in C# by krishna
• 2,540 points
16 views

1 answer to this question.

0 votes
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}

Note that while the cast to (Suit[]) isn't absolutely essential, it does speed up the code by 0.5 nanoseconds.

answered Jun 14 by jyoti
• 1,240 points

Related Questions In C#

0 votes
1 answer

How to implement SOLID principles into an existing project

It will be a lengthy procedure. You ...READ MORE

answered Jun 14 in C# by krishna
• 2,540 points
20 views
0 votes
0 answers

How to force overriding a method in a descendant, without having an abstract base class

This is my code using System; using System.Collections.Generic; using System.Linq; using ...READ MORE

Jun 11 in C# by krishna
• 2,540 points
7 views
0 votes
1 answer

How to iterate over a dictionary?

I have seen this being used. In ...READ MORE

answered Jun 7 in C# by pranav
• 2,580 points
23 views
0 votes
1 answer

How to initialize a list of strings (List<string>) with many string values

Simply remove the () at the end. List<string> ...READ MORE

answered Jun 13 in C# by krishna
• 2,540 points
21 views
0 votes
1 answer
0 votes
2 answers

Is there a .NET equivalent to Apache Hadoop?

Hadoop is a Java-based platform. So, to ...READ MORE

answered Jul 16, 2020 in Big Data Hadoop by Suhana
• 340 points
668 views
0 votes
1 answer

Validate String against USPS State Abbreviations

Try something like this: private static String states ...READ MORE

answered Sep 20, 2018 in IoT (Internet of Things) by Annie97
• 2,160 points
229 views
0 votes
1 answer

Authenticate on an ASP.Net Forms Authorization website from a console app

Essentially, we need to record a regular ...READ MORE

answered Sep 20, 2018 in IoT (Internet of Things) by Annie97
• 2,160 points
263 views
0 votes
1 answer

How to get substring from string containing newlines

If you want to maintain the newline ...READ MORE

answered Jun 14 in C# by jyoti
• 1,240 points
19 views
0 votes
1 answer

How to find the extension of a file in C#

Go to here https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getextension?redirectedfrom=MSDN&view=net-6.0#System_IO_Path_GetExtension_System_String_ string myFilePath = @"C:\MyFile.txt"; string ext ...READ MORE

answered Jun 21 in C# by jyoti
• 1,240 points
26 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP