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?
You can use Jon Skeet's Unconstrained Melody project to do this.
Using Unconstrained Melody you would write:
class Generic<T> where T : IEnumConstraint
Which would accomplish the same thing.
More info about Unconstrained Melody with usage examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With