Previous Page
Next Page

Using Compound Assignment Operators

You've already seen how to use arithmetic operators to create new values. For example, the following statement uses the + operator to create a value that is 42 greater than the variable answer. The new value is then written to the console:

Console.WriteLine(answer + 42);

You've also seen how to use assignment statements to change the value of a variable. The following statement uses the assignment operator to change the value of answer to 42:

answer = 42;

If you want to add 42 to the value of a variable, you can combine the assignment operator and the addition operator. For example, the following statement adds 42 to answer. In other words, after this statement runs, the value of answer is 42 more than it was before:

answer = answer + 42;

Although this statement works, you'll probably never see an experienced programmer write this. Adding a value to a variable is so common that Microsoft Visual C# lets you perform this task in shorthand manner by using the compound assignment operator, +=. To add 42 to answer, an experienced programmer would write the following statement:

answer += 42;

You can use this shortcut to combine any arithmetic operator with the assignment operator, as the following table shows. These operators are collectively known as the compound assignment operators.

Don't write this

Write this

variable = variable * number;
variable *= number;
variable = variable /  number;
variable /= number;
variable = variable % number;
variable %= number;
variable = variable + number;
variable += number;
variable = variable -  number;
variable -= number;
The compound assignment operators share the same precedence and right associativity as the simple assignment operator.

The += operator also functions on strings; it appends one string to the end of another. For example, the following code displays “Hello John” on the console:

string name = "John"; 
string greeting = "Hello "; 
greeting += name; 

You cannot use any of the other compound assignment operators on strings.

Use the ++ and -- operators instead of a compound assignment operator when incrementing or decrementing a variable by 1. For example, replace:
count += 1;

Previous Page
Next Page