I have a generic type that should be specified with an Enum
type (actually, it's one of several specified enums, but I'll settle for System.Enum
).
Of course the compiler balks at code like:
class Generic<T> where T : Enum {}
with a "Constraint cannot be special class 'System.Enum'" exception.
The only solution I've been able to come up so far is using the static type initializer to inspect the type parameter and throw an exception if it is not, in fact, an Enum, like this:
class Generic<T>
{
static Generic()
{
if (typeof(T).BaseType != typeof(Enum))
throw new Exception("Invalid Generic Argument");
}
}
which at least gives me runtime security that it wont we used with a non-enum parameter. However this feels a bit hacky, so is there a better way to accomplish this, ideally with a compile-time construct?