 .NET 1.1C# Compound Assignment Operators
The seventh part of the C# Fundamentals tutorial extends knowledge of the assignment operator into compound assignment operators. These operators permit modification of variable values using the arithmetic functions described earlier in the tutorial.
The Assignment Operator
The use of the basic assignment operator (=) was reviewed in the third part of the C# Fundamentals tutorial. This operator is used to assign a value to a variable. We have used this operator in every part of the tutorial since so no further explanation is necessary.
Compound Assignment Operators
There are further special assignment operators that can be used to modify the value of an existing variable. These are the compound assignment operators.
A compound assignment operator is used to simplify the coding of some expressions. For example, using the operators described earlier we can increase a variable's value by ten using the following code:
value = value + 10;
This statement has an equivalent using the compound assignment operator for addition (+=).
value += 10;
There are compound assignment operators for each of the five binary arithmetic operators (+ - * / %) that we have investigated so far in the tutorial. Each is constructed by using the arithmetic operator followed by the assignment operator. The following code gives some brief examples for addition (+=), subtraction (-=), multiplication (*=), division (/=) and modulus (%=):
int value = 10;
value += 10; // value = 20
value -= 5; // value = 15
value *= 10; // value = 150
value /= 3; // value = 50
value %= 8; // value = 2
Compound assignment operators provide two benefits. Firstly, they produce more compact code (they are often called shorthand operators for this reason). Secondly, the variable being operated upon, or operand, only needs to be evaluated once in the compiled application. This can actually make the code more efficient when executed.
Operator Precedence
The assignment operator and the compound assignment operators have the lowest priority; they appear at the end of the operator precedence table.
| Parentheses Operator |
|---|
| () | | Increment / Decrement Operators |
|---|
| ++(postfix) --(postfix) --(prefix) | | Basic Arithmetic Operators |
|---|
| * / % + - | | Assignment Operator |
|---|
| = | | Compound Assignment Operators |
|---|
| *= /= %= += -= |
|