Does anyone have a very simple example of how to overload the compound assignment operator in C#?
You can't explicitly overload the compound assignment operators. You can however overload the main operator and the compiler expands it.
x += 1
is purely syntactic sugar for x = x + 1
and the latter is what it will be translated to. If you overload the +
operator it will be called.
MSDN Operator Overloading Tutorial
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
According to the C# specification, += is not in the list of overloadable operators. I assume, this is because it is an assignment operator as well, which are not allowed to get overloaded. However, unlike stated in other answers here, 'x += 1' is not the same as 'x = x + 1'. The C# specification, "7.17.2 Compound assignment" is very clear about that:
... the operation is evaluated as x = x op y, except that x is evaluated only once
The important part is the last part: x is evaluated only once. So in situations like this:
A[B()] = A[B()] + 1;
it can (and does) make a difference, how to formulate your statement. But I assume, in most situations, the difference will negligible. (Even if I just came across one, where it is not.)
The answer to the question therefore is: one cannot override the += operator. For situations, where the intention is realizable via simple binary operators, one can override the + operator and archieve a similiar goal.
You can't overload those operators in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With