How to iterate all enum values in Csharp Examples
Enum is a custom class that contains a group of constants. Each Enum object holds constants.
This tutorial explains Multiple ways to iterate Enum constants in C#
One way, using the GetValues
method from the System.Enum
class to get all values in array form. Order is of Enum declaration order. Another way using a Simple for loop with initialized start and end value syntax.
How to iterate all Enum values in C# with an example
Let’s Define enum constants.
public enum DAYS : int{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
There are multiple ways using System.Enum.GetValues method:
System.Enum
class provides the GetValues
and GetNames
Method, which returns an array of Enum constants.
- GetValues - return Array of Objects
- GetNames - Return Array of Strings
For .NET 5 users, use generics
var enums = Enum.GetValues<DAYS>(); // Array of Objects
var values = Enum.GetNames<DAYS>(); //Array of Strings
For .NET 4 users, Syntax is to use typeof for an Enum class.
DAYS[] values= Enum.GetValues(typeof(DAYS))
Once you have an Array of Enum objects, You can iterate using a foreach loop to retrieve Enum and values
foreach (int value in Enum.GetValues(typeof(DAYS)))
{
Console.WriteLine(((int)(DAYS)value)+" - "+((DAYS)value).ToString());
}
Here is a complete example
using System;
public class Program
{
public static void Main()
{
foreach (int value in Enum.GetValues(typeof(DAYS)))
{
Console.WriteLine(((int)(DAYS)value)+" - "+((DAYS)value).ToString());
}
}
}
public enum DAYS : int
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
Output:
1 - Monday
2 - Tuesday
3 - Wednesday
4 - Thursday
5 - Friday
6 - Saturday
7 - Sunday
Another way using for loop with start and end value:
using simple for loop, Initialze start value (DAYS.Monday), increment, do iteration until end value(DAYS.Sunday) meet.
using System;
public class Program
{
public static void Main()
{
for (var i = DAYS.Monday; i <= DAYS.Sunday; i++)
{
Console.WriteLine(i);
}
}
}
public enum DAYS : int
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
Output:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday