Back to Basics – How to iterate though an enumeration (Enum) in C# ?

By | October 31, 2017

The enum type is one of the common features that we used during almost every implementation. While the declarations and usages look very straightforward, there are many things we should be very clear about, and this topic is one of them. How to iterate through an Enum in C#? or can you loop through with all the enum values in C#? – yet another frequently asked question in an interview for the beginners. Well, there are several ways to achieve this. To answer this in a sort way, the Enum class provides the base class for enumerations and Enum.GetNames() method, which is used to retrieve an array of the names and returns a string array of the names.

Let’s try to understand using simple example. Consider you have following Enumeration

enum WorkingDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday
}

 

Check out for more similar .NET Frequently Asked Questions

Now using the Enum.GetNames()  you can iterate through the enumeration as following. Enum.GetNames() required the types of enum as parameters, which you can pass using typeof keywaord. That will retrieve an array of the names of the constants in the WorkingDays enumeration.

foreach (var item in Enum.GetNames(typeof(WorkingDays)))
{
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(WorkingDays)))
{
Console.WriteLine(item);
}

and this will also produce the same output.

Both the approaches works, but now the question would be, what is the difference between Enum.GetNames() and Enums.GetValues() ?
GetNames() will return a string array of the Names for the items in the enum where as the GetValues() will return an array of the values for each item in the Enum.
When we define the enum, all the Enum elements will have an assigned a default values starting from 0. For an example, Monday will have an assigned values 0, and similarly, Friday will have values of 4.

You can assign the custom values as well.

Now, think of this enumerations as Name & Value pairs. Monday = 0, Tuesday = 1, Wednesday = 2, Thursday = 3, Friday = 4

So with , GetNames() will return a string array containing the items “Monday”, “Tuesday” …. …. “Friday”.. on the other hand,  When  used GetValues(),   Actually, GetValues() will return an int array containing 0,1,2,3,4 . You can easily type cast the values.
[

foreach (WorkingDays item in Enum.GetValues(typeof(WorkingDays)))
{
Console.WriteLine(Convert.ToInt32(item));
}

2 thoughts on “Back to Basics – How to iterate though an enumeration (Enum) in C# ?

  1. Pingback: Dew Drop - November 1, 2017 (#2594) - Morning Dew

  2. Pingback: Edition 21# – Late Night Link

Leave a Reply

Your email address will not be published. Required fields are marked *

Verify Captcha * Time limit is exhausted. Please reload the CAPTCHA.