In this post we’ll discuss about “How to iterate over Enum in C#?”. The Enum type is one of the common features that we have used in most of the implementations. Although the statements and usage seem very simple, there are many things we need to understand, and this topic is one of them.
How to iterate through Enum in C#? or can you loop through all Enum values in C#? Another common interview question for new job seekers. Well, there are several ways to achieve this. To answer this question in a sorted way, the Enum class provides a base class for enumerations and the Enum.GetNames() method, which is used to retrieve an array of names and return an array of name strings.
Let’s try to understand using a simple example. Consider that you have the following enumeration.
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday
}
Now using Enum.GetNames() you can iterate over the enumeration as follows.
Enum.GetNames() requires enum types as parameters, which you can pass using keywaord typeof.This will retrieve a constant array of names in the WeekDays enumeration.
foreach (var item in Enum.GetNames(typeof(WeekDays)))
{
Console.WriteLine(item);
}
Once you run this, you will have following output

In another approach, you can also use Enum.GetValues() and iterate through the items.
foreach (var item in Enum.GetValues(typeof(WeekDays)))
{
Console.WriteLine(item);
}

Both the approaches work, but now the question would be, what is the difference between Enum.GetNames() and Enums.GetValues() ?
GetNames() will return a string array of names of the elements in the enumeration, while GetValues() will return an array of values for each element in the enumeration.When we define enumeration, all Enum elements will be assigned a default value starting from 0.For example, Monday will have an assigned value of 0, and similarly Friday will have a value of 4.

Can we assign custom value in above ..YES or NO?
Yes, you can. Now think of these enumerations as Name and Value pairs. Monday = 0, Tuesday = 1, Wednesday = 2, Thursday = 3, Friday = 4 So with, GetNames() will return an array of strings containing the elements “Monday”, “Tuesday” …..”Friday”.
On the other hand, when using GetValues(), it will in fact return an int array containing 0,1,2,3,4. You can easily type the values.
foreach (WeekDays item in Enum.GetValues(typeof(WeekDays)))
{
Console.WriteLine(Convert.ToInt32(item));
}
In above post you have learned about “How to iterate over Enum in C#?”. Hope this will help you in your daily development practices.
You can check more article on our website under C# section HERE or you can also check same on Micrsoft Docs too.
keep developing Keep sharing!!