Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting the generic type parameter to System.Enum

Tags:

c#

enums

generics

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?

like image 299
SWeko Avatar asked Jan 04 '13 16:01

SWeko


1 Answers

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.

like image 115
MattDavey Avatar answered Oct 09 '22 22:10

MattDavey