Solution for overloaded operator constraint in .NET generics

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.

Leave a Comment