I want to make a class that contains basic arithmetical operations with one generic type (it have to be struct) but I can't limit the generic type with something that make sure compiler that this type will be able to do arithmetical operations. Simple example:
T Sum<T>(T x, T y) { return x + y; }
Error: Operator "+" can't be used on T operands. Using limitation lead to the same problem:T Sum<T>(T x, T y) where T: struct { return x + y; }
What name of the class/interface that contains signatures for basic arithmetical operations that I can use in where
construction to make sure compiler that generic type will have ability to work with arithmetical operations? I coudln't even find it in .NET documentaion.
Asked
Active
Viewed 13 times
0

CIRCULARKA
- 11
- 2
-
If only we have `Numeric` abstract class like in *Java* – Dmitry Bychenko Jun 30 '20 at 09:06
-
Thats not possible actually... You have cast them to use their operators. You could also use reflection to get the operators and invoke them. – Legacy Code Jun 30 '20 at 09:08
-
https://github.com/Capgemini/Cauldron/blob/master/Shared/Cauldron.Activator/Reflection/MathR.cs – Legacy Code Jun 30 '20 at 09:24