Iterate over enumeration values in C#

C# topic 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.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Last updated by at .