Saturday, September 12, 2009

C# annoyance -- Generic Enum constraints

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

generic<class T> where T : Enum
public interface class IEnumConstraint
{
// marker interface
};
view raw gistfile1.cpp hosted with ❤ by GitHub

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 --

internal class Constrained<T> : IEnumConstraint<T>
{
}
view raw gistfile1.cs hosted with ❤ by GitHub

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 :