Home > .net 3.5, c#, Microsoft, Visual Studio 2008 > Playing with Enums in Generic Lists

Playing with Enums in Generic Lists

August 14, 2008

A project that I’m currently working on (I’ll post some info on it up later) required iterating and manipulating Enums.  Right or wrong, manipulating these through a List<T> provided the best mix of functionality and performance.

Unfortunately, Enum.GetValues returns an Array, not a List<T>.  I’m sure I could reuse the code later, so I decided to toss it into my common library.  The final method is a static method, though I’d love to know how to get it to operate as an extension method (the “this” keyword extends the actual members of the Enum, not the Enum itself).

public static List<T> ConvertEnumToList<T>()

{

Type enumType = typeof (T);

      

// Check to make sure the type is an Enum since

       // you can’t “where” an enum.

       if (!enumType.IsEnum)

       {

              // TODO: Clean this up; return a more explicit error.

             throw new ArgumentException(

                     @”T must have a base type of System.Enum.”);

}

 

       // Return a list from a casted array.

       return

              new List<T>(Enum.GetValues(typeof (T)) as IEnumerable<T>);

}

Quick and easy—and quite reusable.

Now I can iterate through the Enum, return the descriptions to the presentation layer, etc.

RequiredRules = Conversion.ConvertEnumToList<Rules>();

  1. Amir
    October 28, 2008 at 3:48 pm

    You can easily build a small piece of C++/CLI code to handle extension methods on Enum fields as unlike C#, a generic type can be constrained by enum.

    Declare the class “abstract sealed” (static in c#), declare the methods as static, add ExtensionAttribute on the class and on the methods and just say generic where T : System::Enum, gcnew()

    Small problem, since C# thinks this is impossible, the C# IDE treats it as an extension method where T : new()

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: