.NET Zone is brought to you in partnership with:

My name is Toni Petrina and I am a software developer and an occasional speaker. Although I primarily develop on the Microsoft stack, I like to learn new technologies. My hobbyist projects range from game development, regardless of the technology, to ALM. I spend most of my time with my girlfriend and someday I will learn how to play the guitar properly. Toni is a DZone MVB and is not an employee of DZone and has posted 51 posts at DZone. You can read more from them at their website. View Full User Profile

Iterate Over Enumeration Values in C#

10.02.2012
| 2202 views |
  • submit to reddit
This is just a small method that allows iterating over enumeration values. I needed strong type and LINQ support for enumeration values, but the built-in method returns Array which is unusable. You have to convert each value to the enumeration type using Cast<T>.

The generator function is given as:

static class EnumEx
{
    public static IEnumerable<T> GetValues<T>()
    {
        foreach (T value in Enum.GetValues(typeof(T)))
        {
            yield return value;
        }
    }
}

You can use it in the following manner:

foreach (var value in EnumEx.GetValues<someEnum>())
{
    // ...
}

The official way to achieve the above functionality with built in stuff in .NET 4 is using the following not-so-short code:

foreach (var value in typeof(enumStructureParameters)
                             .GetEnumValues()
                             .Cast<enumStructureParameters>())
{
    // ...
}

Happy coding.

 

Published at DZone with permission of Toni Petrina, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)