Search code examples
c#genericstype-constraints

How to constraint a generic to be of type enum?


Consider the following code:

class Base<T>
{
 //Base members
}

I want the generic T to be an enum (using constraints if possible). How can I do this in C#?

EDIT:
Using code contracts -introduced by Akash Kava- also seems like a nice way. I managed to get it to produce a run time error which is useless. Here's the code I tried. It should be possible to generate a compile time warning but I can't get it to work.


Solution

  • This is supported at the IL level but not in C#. You may take a look at unconstrained melody written by Jon Skeet which allows you to achieve that. And here's the corresponding blog post where he explains in details.