Multiplication operator overload modifying original variable (C#)?
c#, operators, reference, types
Solution
You shouldn't be modifying the existing matrix with your code. The signature screams that it is creating a new `Matrix` and returning it.
I'm not positive what your copy method/constructor is, but don't assign `m1` to `ret`; you should be making a copy of `m1`, modifying the copy, and returning the copy, leaving `m1` unchanged.
public static Matrix operator *(Matrix m1, double c)
{
Matrix ret = m1.Clone(); //not sure what your "copy" method is
//do the multiplication on ret
return ret;
}
Problem
I'm working on a matrices library as a learning project, and in doing so I've overloaded the * operator to perform matrix multiplication. I've also overloaded it to handle scalar multiplication (multiplying every element of the matrix by a double). My problem is that when the following code is run, both test2 and test are being modified, which is undesired. ``` Matrix test2 = 2 * test; ``` I'm sure this is a problem with the fact that Matrix is a class, and is therefore being passed by reference, but without changing Matrix to a struct (something I don't think will be suitable, and when tried doesn't seem to work), I can't see any way of resolving this. How would I fix this? The actual operator code is ``` public static Matrix operator *(Matrix m1, double c) { Matrix ret = m1; for (long i = 0; i < ret.Width; i++) // Iterate over the rows. { for (long p = 0; p < ret.Height; p++) // Iterate over the columns. { ret[i, p] *= c; } } return ret; } ```