chris12892
chris12892

Reputation: 1644

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#?

Upvotes: 6

Views: 1501

Answers (3)

user492238
user492238

Reputation: 4084

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.

Upvotes: 4

Stephan
Stephan

Reputation: 5488

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);
}

Upvotes: 12

Steve Dennis
Steve Dennis

Reputation: 1373

You can't overload those operators in C#.

Upvotes: 2

Related Questions