Search code examples
c#genericsoperator-overloading

How to overload operators on a generic class if its generic type has those operators?


Let's say I have a generic matrix type:

class Matrix<T>
{
    private T[,] _data;
}

Is it possible to overload the + operator on Matrix<T> if and only if T has an overloaded + operator?

Having written a lot of Rust lately, I was hoping this would work:

class Matrix<T>
{
    private T[,] _data;

    public static Matrix<T> operator+(Matrix<T> lhs, Matrix<T> rhs)
        where T: IAdditionOperators<T>
    {
        // ...
    }
}

Sadly, where can only be applied to generic parameters of the method itself, not of its containing class.

I know I can drop the where clause and use dynamic in the method body to perform the addition, but the performance implications are not acceptable in my case.

This question is similar but would be solved with the new IAdditionOperator<T> interface in C# 11. However, I want my Matrix<T> type to work with types T that don't have an addition operator too. (It's okay if this is checked at runtime though.)

Maybe something with a subclass and implicit conversions?


Solution

  • This is not currently possible as far as I know.

    The simplest workaround would be extension methods:

    static class MatrixExt{
        public static Matrix<T> Add(this Matrix<T> a, Matrix<T> b) where T: IAdditionOperators<T>{
              ...
         }
    }
    

    This would require that the actual data is public accessible somehow.

    There have been talks about "extension operators", but nothing that has been added to the language.