As in C #, for a generic method, set the restriction to an integer type only (byte, sbyte, short, ushort, int, uint, long, ulong)

public T example<T>(this T value) where T (...)???? 
  • They say that there is no native support, but probably something can be done like that. - post_zeew
  • @post_zeew thanks - Vadim Prokopchuk

1 answer 1

No As constraints for generalizations only the following constructions can be used:

  • where T: struct
  • where T: class
  • where T: new ()
  • where T: <base class name>
  • where T: <interface name>
  • where T: U, where U is another type parameter

As workarounds, you can use the following options:

  • create overload for each type
  • leave the T parameter without restrictions and check the type at the beginning of the method (this is, for obvious reasons, a “weaker” solution)