BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# 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 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:

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 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.

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) --(prefix)
Basic Arithmetic Operators
* / % + -
Assignment Operator
=
Compound Assignment Operators
*= /= %= += -=
20 August 2006