How to iterate over Enum in C#
By FoxLearn 1/9/2025 4:34:36 AM 52
How can you loop through all Enum values in C#?
This is a frequent question, especially during technical interviews for new developers. The good news is that there are multiple ways to iterate over Enum values in C#. One of the most efficient approaches involves using the Enum.GetNames()
method.
The Enum
class is a base class for all enumerations, and Enum.GetNames()
returns an array of names corresponding to the enumeration values.
enum WeekDays { Monday, Tuesday, Wednesday, Thursday, Friday }
Using Enum.GetNames()
, you can iterate over the WeekDays
enumeration as follows:
foreach (var day in Enum.GetNames(typeof(WeekDays))) { Console.WriteLine(day); }
When you run the above code, it will produce the following output:
Monday Tuesday Wednesday Thursday Friday
Using Enum.GetValues()
You can also loop through the values of an Enum using Enum.GetValues()
. This method returns an array of the underlying Enum values, which can be iterated over like this:
foreach (var value in Enum.GetValues(typeof(WeekDays))) { Console.WriteLine(value); }
Output:
Monday Tuesday Wednesday Thursday Friday
Difference Between Enum.GetNames() and Enum.GetValues()
Both methods allow you to iterate through an Enum, but there is a key difference:
Enum.GetNames()
returns an array of strings containing the names of the Enum values.Enum.GetValues()
returns an array of the actual Enum values, typically as integers.
For example, if the WeekDays
enum is defined as:
enum WeekDays { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5 }
In this example:
Enum.GetNames()
will return:["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
Enum.GetValues()
will return:[1, 2, 3, 4, 5]
Custom Enum Values
Can you assign custom values to your enum? The answer is yes! When you define an Enum, you can explicitly assign values to its elements.
enum WeekDays { Monday = 10, Tuesday = 20, Wednesday = 30, Thursday = 40, Friday = 50 }
Now, when you use Enum.GetValues()
, it will return the corresponding values:
foreach (WeekDays day in Enum.GetValues(typeof(WeekDays))) { Console.WriteLine((int)day); }
Output:
10 20 30 40 50
In this post, we explored how to iterate over Enum values in C#, comparing two methods: Enum.GetNames()
and Enum.GetValues()
. Both methods have their specific use cases: Enum.GetNames()
gives you a string array with the names, while Enum.GetValues()
returns the actual underlying values of the enum elements. Additionally, you can assign custom values to Enum elements to suit your needs.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#