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?
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
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...
}
}
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly