5

Possible Duplicate:
Create Generic method constraining T to an Enum

Given a generic method that only operates on enum values

static void <T> method(T enum) where T ?????
{
     // do something with enum...
}

How do I constrain T such that only enum values are accepted? I've tried using struct however this disallows the use calling my method with a nullable enum type.

Community
  • 1
  • 1
Carlo V. Dango
  • 13,322
  • 16
  • 71
  • 114

2 Answers2

4

Generic constraints on enum types are impossible in C#, but are possible in IL. Have a look at Jon Skeet's project, Unconstrained Melody, it will allow you to constraint your generic methods to enums.

Igal Tabachnik
  • 31,174
  • 15
  • 92
  • 157
  • Thats an example of how to do this using IL rather than a library to let you do this yourself, but very interesting all the same! – Justin Sep 08 '11 at 11:11
2

In C# you can't. For some reason I don't know the C# specification explicitly forbids System.Enum as a constraint.

And even then it wouldn't accept nullable enums because nullable enums are no enums.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262