Saturday, 4 March 2017

c# - Possible to constrain generic type to enums?




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




I have tried



public class Foo 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 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.



Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...