Solution for overloaded operator constraint in .NET generics

blackwing picture blackwing · Sep 29, 2008 · Viewed 16.7k times · Source

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?

Answer

Marc Gravell picture Marc Gravell · Sep 29, 2008

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:

T result = Operator.Add(first, second); // implicit <T>; here

It can be downloaded as part of MiscUtil

Additionally, in C# 4.0, this becomes possible via dynamic:

static T Add<T>(T x, T y) {
    dynamic dx = x, dy = y;
    return dx + dy;
}

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

interface ICalc<T>
{
    T Add(T,T)() 
    T Subtract(T,T)()
} 

etc, but then you need to pass an ICalc<T>; through all the methods, which gets messy.