Home of the AlmostImplementedException

How to iterate through an enum

On occasions it’s necessary to iterate through an enum. Maybe you need to show all values or names or want to use all values in a unit test.
Since .Net 4 there are two ways to get the names and values, but as you will see the old way is the better choice.

First of all we need an enum to iterate through. Lets reuse the Ingredients-enum and iterate through the names:

As you may have noticed there are two ways to get all names. The first one is Enum.GetNames which will work in every .Net version. The second one is GetEnumNames on the type of the Enum, which is slightly faster (if you do it 1.000.000 times you’ll save around 5 ms) but only works with .Net 4 or higher.
Since you shouldn’t iterate through an enum to often (at least without caching) and the difference is only marginal, the first way is the best.

Iterating through the values of an enum is way more expensive (something around 20 times) then through the names.

This time both ways are equally fast and like for the name the first one works with every .Net version, the later only since .Net 4. Try both to see for youself.

Both functions are also a very good example of the boxing/unboxing mechanism in C#. Both, GetValues and GetEnumValues return a System.Array and foreach is using the non-generic implementation of IEnumerable for the iteration. Which means every enum value is boxed into an object-box and then unboxed by the cast of your foreach.
Therefore we need to cast the array to Ingredients[] to prevent the boxing/unboxing and since the cast is a simple reference conversion its very fast:

This simple change saves you around 40% of the execution time.
Like for the names you should use the first way in your code since this one will work with every .Net version and is as fast as the other one.

If you need the integer value of the enum you can cast the array in your foreach to int[] or just the variable ing when you use it.
And here is a little example how to write the name and value to the console:

I hope this will help you next time you need to iterate through an enum.
Until next time.

Share :

, ,

Leave a Reply