Search code examples
c#.netgenericscilcil-metadata

Why cant you require operator overloading in generics


In C++, you can write code like this:

template<class T>
T Add(T lhs, T rhs)
{
    return lhs + rhs;
}

But, you can't do something like this in C#:

public static T Add<T>(T x, T y) where T : operator+
{
    return x + y;
}

Is there any reason why? I know it could be accomplished through reflection (generic Add with objects and then run type checking over it all), but that's inefficient and doesn't scale well. So, again, why?


Solution

  • There is no inherent reason this could not exist. The way generic type constrains are implemented is through interface calls. If there were an interface that provided an operator+ this would work.

    This interface would be required for all relevant types, though, to be as general as the C++ template-based analog.

    Another issue would be that .NET has no multiple dispatch. The interface call would be asymmetric: a.Plus(b) could mean something different than b.Plus(a). Equals has the same problem, btw.

    So this issue probably did not meet the "usefulness"-bar or the "cost/utility"-bar. This is not an issue of impossibility, but of practical concerns.

    Proof that it is possible: ((dynamic)a) + ((dynamic)b).