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, 2022 in C# by krishna
• 2,820 points
409 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, 2022 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, 2022 in C# by krishna
• 2,820 points
550 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, 2022 in C# by krishna
• 2,820 points
984 views
0 votes
1 answer

How to iterate over a dictionary?

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

answered Jun 7, 2022 in C# by pranav
• 2,590 points
441 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, 2022 in C# by krishna
• 2,820 points
1,710 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
1,709 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
923 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
888 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, 2022 in C# by jyoti
• 1,240 points
1,463 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, 2022 in C# by jyoti
• 1,240 points
603 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP