Previous Page
Next Page

Understanding Compound Assignment

C# does not allow you to declare any user-defined assignment operators. However, a compound assignment operator (such as +=) is always evaluated in terms of its associated operator (such as +). In other words, this:

a += b;

Is automatically evaluated as this:

a = a + b;

In general, the expression a @= b (where @ represents any valid operator) is always evaluated as a = a @ b. If you have declared the appropriate simple operator, it is automatically called when you use its associated compound assignment operator. For example:

Hour a = ...;
int b = ...;
a += a; // same as a = a + a
a += b; // same as a = a + b

The first compound assignment expression (a += a) is valid because a is of type Hour, and the Hour type declares a binary operator+ whose parameters are both Hour. Similarly, the second compound assignment expression (a += b) is also valid because a is of type Hour and b is of type int. The Hour type also declares a binary operator+ whose first parameter is an Hour and whose second parameter is an int. Note, however, that you cannot write the expression b += a because that's the same as b = b + a. Although the addition is valid, the assignment is not because there is no way to assign an Hour to the built-in int type.

Previous Page
Next Page