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.
source share