Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to constrain generic type to enums? [duplicate]

Tags:

c#

enums

generics

I have a generic class Foo<T> where I want to constrain T to be an enum type. Is this possible in C#?

I have tried

public class Foo<T> where T : enum   // COMPILATION ERROR

but this approach only seem to work for class and struct.

Likewise, attempting to constrain T to an underlying enum type will also not work:

public class Foo<T> where T : int    // COMPILATION ERROR

since int is not a class or interface.


EDIT I realize now that similar questions have been posted before, and eventually this question can be removed. One question that is even more related to my question, and that also contains the same answer as below, is this.

UPDATE SEP 13, 2018 In the latest minor C# version, 7.3, it is now possible to constrain the generic type to an Enum. For more details, see here.

like image 607
Anders Gustafsson Avatar asked Nov 15 '13 13:11

Anders Gustafsson


1 Answers

That isn't valid in the C# spec and implementation, but it is in IL.

Jon Skeet made a library to get around this called Unconstrained Melody:

https://code.google.com/p/unconstrained-melody/

Though I've never used it so I cannot offer any insight into how to take advantage of this.

like image 151
Adam Houldsworth Avatar answered Oct 21 '22 11:10

Adam Houldsworth