views:

145

answers:

2

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

+1  A: 

You can't overload those operators in C#.

Steve Dennis
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
@dss539 - Indirectly, sure. I was just answering his question.
Steve Dennis
+7  A: 

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
vitorbal
I know it can be overloaded in that way, I just want a very simple code example. Anyone?
chris12892
Thanks, that's exactly what I needed
chris12892