The Assignment Operator
The basic assignment operator (=) was reviewed in the third part of the C# Fundamentals tutorial. This operator is used to assign value to variables. We have used the operator in every part of the tutorial since, so no further explanation is necessary.
Compound Assignment Operators
There are further 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:
This statement has an equivalent using the compound assignment operator for addition (+=).
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 using the arithmetic operator followed by the assignment operator. The following code gives 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, will only be evaluated once in the compiled application. This can make the code more efficient.
The assignment operator and the compound assignment operators have the lowest priority; they appear at the end of the operator precedence table.
|Increment / Decrement Operators|
|++(postfix) --(postfix) ++(prefix) --(prefix)|
|Basic Arithmetic Operators|
|* / % + -|
|Compound Assignment Operators|
|*= /= %= += -=|
20 August 2006