2

What I need is to overload Operator + in C# so I can sum 2 matrixes.

What I have is this function:

public int[,] operator+(int[,] matriz1, int[,] matriz2)
    {
        int[,] retorno = new int[4, 4];
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                retorno[i, j] = matriz1[i, j] + matriz2[i, j];
            }
        }
        return retorno;
    }

When I do this for example (WT, W1, W2 are all int[4,4]):

WT = W1 + W2;

I get an error saying: operator + cannot be applied to operands of type int[,] and int[,], what am I doing wrong and how can I solve it?

Mario Fuentes
  • 47
  • 2
  • 5

3 Answers3

6

Well, for one, before you even try to use the operator, try compiling just the operator method. It won't compile, and the error message is telling:

error CS0563: One of the parameters of a binary operator must be the containing type

This means exactly what it says: if you write a class C, you can write an addition operator for C + <any type> (or <any type> + C). You cannot define an operator that does not involve C in some way. So, simply, since you're not the one writing the int[,] class, you can't define an operator for it.

Your best bet is probably to define a Matrix class yourself, then you can define whatever operators you want on it. For instance;

public class Matrix
{
    private readonly int[,] _values;

    public int this[int x, int y] {
        get { return _values[x, y]; }
    }

    public Matrix(int[,] values) {
        _values = values;
    }

    public static Matrix operator +(Matrix x, Matrix y) {
        int[,] m0 = x._values;
        int[,] m1 = y._values;
        int[,] newMatrix = /* add m0 and m1 */;
        return new Matrix(newMatrix);
    }
}
Jacob
  • 1,699
  • 10
  • 11
3

You can't write operators for non-custom types:

Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

Source: MSDN

An alternative might be to write an extension method:

public static class MatrixExtensions {
    public static  int[,] Add(this int[,] matriz1, int[,] matriz2)
    {
        int[,] retorno = new int[4, 4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                retorno[i, j] = matriz1[i, j] + matriz2[i, j];
            }
        }
        return retorno;
    }
}

And use it like this:

int[,] a = ...
int[,] b = ...
int[,] c = a.Add(b);
Julián Urbano
  • 8,378
  • 1
  • 30
  • 52
  • I am not convinced by this solution. This is not overwriting the operator, you just have implemented a method. It is not the same to use the syntax of A.Add(B) with the syntax of A + B. First of all, it is not clear for your teammates from the start whether Add adds B to A and changes A, or it just calculates the value. It is also unclear for your teammates whether Add returns a matrix or returns void. They have to look at your method. In the other hand, if they see A + B in the code, it will be clear for them. – Lajos Arpad Apr 12 '13 at 02:04
  • @LajosArpad I know I'm just making up a new method...I say that explicitly. You can't use operators in an `int[,]`, so if you want something similar, you must write your own class, which I don't think is any more clear. You don't know if it returns `void`? Read the damn method signature. – Julián Urbano Apr 12 '13 at 02:09
  • There is no point to be rude. First of all, I don't want to read a method signature if you could write better code. I want to see A + B instead of A.Add(B). It is that simple. Also, maybe I was not clear enough for you. I will be more explicit, so you will understand... The op already talks about matrices and operator overwriting. This means he should create a class called Matrix and should overwrite the + operator. You would have probably understood this from my first comment if you wouldn't use all your energy to be rude. – Lajos Arpad Apr 12 '13 at 02:15
  • I didn't mean to be rude, so let's not be sarcastic either. I did understand it the first time, it's what others suggest. Also note that the question was "why not", so I answered "because". I merely propose an alternative. The pro is that it uses the built-in type, the con is that (maybe) its behavior is not clear enough without intellisense/documentation. The pro of using the operator is that it's behavior is (should be?) implicit, but the con is that you're creating a whole new class to use matrices, when there is a built-in type for that. So custom whole class vs. method. – Julián Urbano Apr 12 '13 at 02:23
  • Yes, that's the base of the debate, I agree with you. It is obvious that there are many solutions to this problem. However, the addition of matrices is a mathematical term. A + B has a meaning. MyMatrix A = B + C is evident after a single glance. On the other hand MyMatrix A = B.Add(C) is not evident. It is clear Add returns a MyMatrix, but it is not clear what will happen to B. You can create a static method MyMatrix.Add(MyMatrix A, MyMatrix B), but it is not as clear on usage as addition. I believe this should be a class, the op probably implements other methods for matrices too. – Lajos Arpad Apr 12 '13 at 02:28
  • I'm sorry, I have to disagree: if I see `MyMatrix A = B.Add(C)` it is clear to me what it does. But yes, whatever the OP decides to do. – Julián Urbano Apr 12 '13 at 02:33
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/28069/discussion-between-lajos-arpad-and-julian-urbano) – Lajos Arpad Apr 12 '13 at 02:34
3

It's not working in this case because operator overloading has to be done for the class it works on and in this case you're only overloading it for whatever class this method is contained within. Basically, when you do W1 + W2 it looks for a '+' operator defined for int[,], which doesn't exist for that built-in type.

For it to work on matrices as you're trying to do, you would need to make a Matrix class (perhaps internally storing its values as a 2d integer array as you're doing) and then overload the operator for that class.

Animatinator
  • 410
  • 2
  • 6