What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can’t have operator overloading.
What is the best way to achieve this?
There is no immediate answer; operators are static, and cannot be expressed in constraints – and the existing primatives don’t implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than).
However; if you just want it to work, then in .NET 3.5 there are some options…
I have put together a library here that allows efficient and simple access to operators with generics – such as:
It can be downloaded as part of MiscUtil
Additionally, in C# 4.0, this becomes possible via
dynamic:I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as
etc, but then you need to pass an
ICalc<T>;through all the methods, which gets messy.