Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to overload compound assignment operator in C#?

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

like image 835
chris12892 Avatar asked May 19 '10 20:05

chris12892


3 Answers

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);
}
like image 167
Stephan Avatar answered Oct 21 '22 03:10

Stephan


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.

like image 42
user492238 Avatar answered Oct 21 '22 04:10

user492238


You can't overload those operators in C#.

like image 21
Steve Dennis Avatar answered Oct 21 '22 03:10

Steve Dennis