Please feel free to offer more clarification if my answer seems awkward.
There are no general restrictions for operators in C #, at least. Since John Skeet has proven that Unconstrained Melody , restrictions can really be valid in the CLR itself.
The best you can do with restrictions is to provide interfaces / user classes that expose the actions you need. You will not be able to provide a primitive (if you may not be executing the implicit operator), but it will at least allow you to create common code for the mathematical part.
Common constraints allow the compiler to infer available members based on the lowest common denominator (as defined by a constraint or absence). In most cases, generics are unlimited and therefore only give you the semantics of object .
Alternatively, avoid using restrictions and use
dynamic to temporarily store a shared variable, and then make the assumption (using duck input) that it has the corresponding operators:
class Program { static void Main(string[] args) { var result = Add<int, long, float>(1, 2); Console.WriteLine(result);
This is DLR-related and will have some performance overhead (I don't have exact numbers), especially if you assume that the calculations will be performance critical.
I'm not sure what you mean by "declare the same generic type multiple times", this works:
class Tuple<T1, T2> // etc. var myTuple = new Tuple<int, int>(1, 2);
Adam houldsworth
source share