APR
10
2008

I later expanded this out into a full Enum<T> strongly typed helper.

I can’t be the only person in the world who wants to foreach over the values of an enum otherwise Enum.GetValues(Type enumType) wouldn’t exist in the framework. Unfortunately it didn’t get any generics love in .NET 2.0 and unhelpfully returns an array.

Thanks to the power of LINQ you can do this:

foreach(var customerType in Enum.GetValues(typeof(CustomerTypes)).Cast<CustomerTypes>()))

That is okay, but this is more concise:

foreach(CustomerTypes customerType in Enums.Get<CustomerTypes>())

The tiny class to achieve that is, of course:

using System.Collections.Generic;
using System.Linq;

public static class Enums {
  public static IEnumerable<T> Get<T>() {
    return System.Enum.GetValues(typeof(T)).Cast<T>();
  }
}

Great.

[)amien

0 responses

  1. Avatar for

    Information is only used to show your comment. See my Privacy Policy.