Playing with Enums in Generic Lists
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.
// 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.
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>();