0

Is it possible to define a generic class where T can belong only to value type (such as int, double and so on)?

TOP KEK
  • 2,593
  • 5
  • 36
  • 62
  • 1
    Apologies, closed it off without fully reviewing the linked answers (not used to that gold badge close feature just yet!), although the question header was the same, the actual question was much different. Though I am surprised I cannot find a duplicate of this somewhere. – Adam Houldsworth Jun 26 '14 at 09:01

2 Answers2

5

yes, you need a struct constraint:

class OnlyStructs<T> where T : struct { }

But you should be aware of that this also allows user-defined structs, not just int,double etc.. Unfortunately there is no built-in way to restrict T for only specific types like where T : int,double,float.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
4

Use struct in generic constraint where T : struct

Sanja Melnichuk
  • 3,465
  • 3
  • 25
  • 46