I have the following problem:
I can statically overload the operator+ to add some custom objects:
public static obj operator+(obj A, obj B)
{
obj ret = new obj();
ret.magic = A.magic + B.magic;
return ret;
}
The return is a new object that got whatever summed by operator+. Which is perfect.
But when writing…
obj A, B;
/* ... */
A += B;
This would not increment A
, it would construct a new A
. So A
does not only hold a new value, it is a completely new object, which is not what I want when I write A += B
.
So what is the C# approach to overloading unary assignment operators like I do in C++?
Because, just leaving out the first line in above static operator+ - function will change A
in the following scenario:
obj C = A + B;
so, for pretty obvious reasons:
after A += B
, A
should still be the same object.
Of course, I can just implement it the way it should be:
public obj add(obj B)
{
magic += B.magic;
return this;
}
public static obj operator+(obj A, obj B)
{
obj ret = new obj();
ret.magic = A.magic;
ret.add(B);
return ret;
}
But then, it still wont get called on A += B
, which will break expectations.