We often find a usecase where we have to iterate through the values of something to get the job done.
This iteration of looping can be for some calculations or display stuff, but we always iterate on lists or arrays and get data out of each item in that list or array.
In this blog post, we will use loops, but not on list or array, we will iterate an enum today.
How Is Iterating An Enum In C# Any Useful?
Well just like we loop through lists and do something, the same theory applies here.
When we iterate on an enum, we want to go through each and every value inside the enum and want to perform an action.
Iterating Enums In C#
Let's say you have an enum that holds the value of all the months of the year.
Our enum will look something like this:
public enum Month { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12 }
To iterate on the values of the enum, we have to get all the values first into a list.
For that, we use the Enum.GetValues method.
var allMonths = Enum.GetValues
Now that we have the list, we can use a loop of any sort on this array. In our example, we will use the foreach loop and display all the values of the enum by using the .ToString() method on the enum value.
var allMonths = Enum.GetValues
We can do this in one single line as well, getting all the enum values in the foreach loop and we will get the same result.
foreach (var month in Enum.GetValues