5

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.

Anders Gustafsson
  • 15,837
  • 8
  • 56
  • 114
  • You are right. I will remove this question. Thanks anyway to those of you who have provided informative answers. – Anders Gustafsson Nov 15 '13 at 14:05
  • @AndersGustafsson Fair play. – Ondrej Janacek Nov 15 '13 at 14:08
  • @OndrejJanacek Just to be sure, you mean this in a non-ironic way, right? In that case, thanks. I *am* a little concerned about removing the question since other people have received upvotes on their answers. – Anders Gustafsson Nov 15 '13 at 14:10
  • @AndersGustafsson Yes, it is not irony. Your question will be removed sooner or later so why bother mods when you realize your mistake and you can remove it yourself? – Ondrej Janacek Nov 15 '13 at 14:15
  • @Ondrej Just for the record, it turned out that I cannot remove it myself since it already has received an answer. I *have* flagged it for deletion though, so it will go away eventually :-) – Anders Gustafsson Nov 15 '13 at 14:20

1 Answers1

6

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.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
  • many thanks for pointing this out. Since my question obviously has been stated before, I will remove the question though. Hope you are OK with that. – Anders Gustafsson Nov 15 '13 at 14:07
  • @AndersGustafsson but this answer hasn't been given before, has it? I'd say, don't delete the question – dcastro Nov 15 '13 at 14:16
  • @dcastro Actually, it has, although not in the referred question above, I think. [Here](http://stackoverflow.com/a/14160744/650012) is one answer that I found. I will try to add that question to the post above. – Anders Gustafsson Nov 15 '13 at 15:28