I am trying to do operator overloads for +=, but I can’t. I can only make an operator overload for +.
How come?
Edit
The reason this is not working is that I have a Vector class (with an X and Y field). Consider the following example.
vector1 += vector2;
If my operator overload is set to:
public static Vector operator +(Vector left, Vector right)
{
return new Vector(right.x + left.x, right.y + left.y);
}
Then the result won’t be added to vector1, but instead, vector1 will become a brand new Vector by reference as well.
Overloadable Operators, from MSDN:
Even more, none of assignment operators can be overloaded. I think this is because there will be an effect for the Garbage collection and memory management, which is a potential security hole in CLR strong typed world.
Nevertheless, let’s see what exactly an operator is. According to the famous Jeffrey Richter’s book, each programming language has its own operators list, which are compiled in a special method calls, and CLR itself doesn’t know anything about operators. So let’s see what exactly stays behind the
+and+=operators.See this simple code:
Let view the IL-code for this instructions:
Now lets see this code:
And IL-code for this:
They are equal! So the
+=operator is just syntactic sugar for your program in C#, and you can simply overload+operator.For example:
This code will be compiled and successfully run as:
Update:
According to your Update – as the @EricLippert says, you really should have the vectors as an immutable object. Result of adding of the two vectors is a new vector, not the first one with different sizes.
If, for some reason you need to change first vector, you can use this overload (but as for me, this is very strange behaviour):