Pass a restricted type to a method

There are several similar questions here, but not one of them answers my question.

I want to create a method that takes an Enum type and generates a List of ListItems for the user interface. Something with such a signature might work:

public static List<ListItem> ListItemListFromEnum(Type t) { ... } 

But I would prefer not to accept any type (t should be an Enum type) So I could do something like this:

 public static List<ListItem> ListItemListFromEnum(Enum e) { Type t = e.GetType(); } 

and just pass an enumeration method of the correct type. This will work fine, but I would really like to take a type parameter (as in my first example), but make it be an Enum type.

Is it possible? Is there a way to do this with generics? Thanks

+4
source share
2 answers

If you want to do this method:

 public static List<ListItem> ListItemsListFromEnum<T>() where T:Enum 

Then this is not possible in C #. However, Jon Skeet has compiled Unconstrained Melody , which adds functionality with some IL processing messages. It seems that the C # compiler obeys these restrictions, it simply cannot declare them.

However, if this is not what you want, you can just accept Type as you are and check IsEnum . If so, throw an exception.

 public static List<ListItem> ListItemListFromEnum(Type t) { if (!t.IsEnum) { throw new ArgumentException("Type must be an enumeration", "t"); } } 

Similarly, you can do the same with the general:

 public static List<ListItem> ListItemListFromEnum<T>() { if (!typeof(T).IsEnum) { throw new ArgumentException("Type must be an enumeration", "t"); } } 

The only negative is that you get an exception at runtime, not compilation time.

+6
source

You can accept a Type and then throw it away if that type is not an enum type. This is probably the best way (until C # allows you to fill out typical placeholders like enum , if ever).

 public static List<ListItem> ListItemListFromEnum(Type t) { if (!t.IsEnum) { throw new ArgumentException("The type passed in must be an enum type."); } // ... } 

This is what C # itself does with many static methods of the enum class (e.g. Enum.GetEnumNames() ).

+1
source

All Articles