Saturday, September 12, 2009

C# annoyance -- Generic Enum constraints

I discovered the other day that you can compile this in C++/CLI --

while the equivalent in C# tells you you can't constrain to System.Enum -- and the language deliberately goes out of its way to specifically prevent this. Nor can you tag enums with marker interfaces (they're sealed classes).

Unfortunately, even though you have the juicy IL code for IEnumConstraint, you can't actually use it in C# like --

you get

The type 'T' cannot be used as type parameter 'T' in the generic type or method 
'EnumConstraint<T>'. There is no boxing conversion or type parameter
conversion from 'T' to 'System.Enum'.

and you end up being driven back to the previous problem.

No comments :