6

Does anyone have a very simple example of how to overload the compound assignment operator in C#?

chris12892
  • 1,554
  • 2
  • 17
  • 31

3 Answers3

12

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);
}
Stephan
  • 5,340
  • 2
  • 22
  • 31
4

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.

user492238
  • 4,034
  • 1
  • 19
  • 26
2

You can't overload those operators in C#.

Steve Dennis
  • 1,333
  • 10
  • 10
  • 2
    Stephan's post indicates that you can. Of course you can't override it orthogonally from the + operator, but hey, it's technically possible. – dss539 May 19 '10 at 21:04
  • @dss539 - Indirectly, sure. I was just answering his question. – Steve Dennis May 19 '10 at 21:46
  • @dss539 - It's "technically possible"? If anything, "technically possible" is exactly what it is not. – Tod Hoven May 18 '12 at 20:30
  • @Tod You can overload the + operator and thereby change the behavior of the += operator. So yes, it is possible. – dss539 May 22 '12 at 22:52