6

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

chris12892
  • 1,634
  • 2
  • 18
  • 36

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,430
  • 2
  • 23
  • 31
  • here is a good article on the subject of overloading operators in C#: http://www.informit.com/articles/article.aspx?p=101373&seqNum=15 – vitorbal May 19 '10 at 20:57
  • I know it can be overloaded in that way, I just want a very simple code example. Anyone? – chris12892 May 19 '10 at 23:03
  • 4
    'x += 1 is purely syntactic sugar for x = x + 1' this is not completely correct. See my answer. – user492238 Mar 03 '11 at 08:54
  • Also this explains the differenec between x+=1 and x=x+1: http://blogs.msdn.com/b/ericlippert/archive/2011/03/29/compound-assignment-part-one.aspx – Yuf Aug 09 '11 at 14:28
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,094
  • 1
  • 20
  • 26
2

You can't overload those operators in C#.

Steve Dennis
  • 1,343
  • 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