How can I Enumerate an enum in C#?


How can I Enumerate an enum in C#? Here is my current code, and it does not works:

public enum DayOfWeek
{
    Mon,
    Tues,
    Wed,
    Thur,
    Fri,
    Sat,
    Sun
}

public void EnumerateAllDaysOfWeekMethod() 
{
    foreach (DayofWeek dow in DayofWeek) 
    {
       // DoSomething with dow;
    }
}

And gives the following compile-time error, so how to solve it and loop through each day?


Asked by:- jaya
1
: 2599 At:- 1/23/2018 7:39:55 AM
C# Enums loop-enumerate-enums-using-C#







2 Answers
profileImage Answered by:- vikas_jk

You can use GetValues method to iterate through enums in C#, so your code will be

var values = Enum.GetValues(typeof(DayofWeek));

so your complete code will be

foreach(var item in Enum.GetValues(typeof(DayofWeek)))
{
//do something here
}

OR

Using GetNames

Enum.GetName: Retrieves an array of the names of the constants in a specified enumeration.

using System;
public enum DayOfWeek
{
    Mon,
    Tues,
    Wed,
    Thur,
    Fri,
    Sat,
    Sun
}
					
public class Program
{
	public static void Main()
	{
		 foreach (var name in Enum.GetNames(typeof(DayOfWeek)))
        {
            Console.WriteLine(name);
        }
	}
}

Output:

Mon
Tues
Wed
Thur
Fri
Sat
Sun

I have explained all the details of enum  in C# in this article, take a look

https://qawithexperts.com/article/c-/understanding-enums-in-c-its-advantages-with-example/90

2
At:- 1/23/2018 4:53:36 PM Updated at:- 12/6/2022 6:52:27 AM
Ohh great, thanks for your well explained article 0
By : jaya - at :- 2/3/2018 8:01:39 AM


profileImage Answered by:- Sam

Loop using "GetValues" method, here is sample code

foreach (var val in Enum.GetValues(typeof(DayofWeek)))
{
   Console.WriteLine(val);
}

You can also create custom helper functions too:

public static class EnumUtil {
  public static IEnumerable<T> GetValues<T>() {
    return Enum.GetValues(typeof(T)).Cast<T>();
  }
}


//Call it like..
var values = EnumUtil.GetValues<DaysOfWeek>();

 you can also use Enum.GetName(typeof())

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (string name in Enum.GetNames(typeof(Suits)))
    {
        System.Console.WriteLine(name); //Prints Spades, Hearts etc...
    }
}
1
At:- 2/21/2018 10:12:23 AM Updated at:- 2/21/2018 10:16:03 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use