Increment and Decrement Operators

A common requirement is to add a value to a variable, subtract a value from a variable, or otherwise change the mathematical value, and then to assign that new value back to the original variable.

Calculate and Reassign Operators

Suppose you want to increment the mySalary variable by 5000. You can do this by writing:

mySalary = mySalary + 5000;

In simple arithmetic, this would make no sense, but in C# this line means “add 5000 to the value in mySalary, and assign the sum back to mySalary.” Thus, after this operation completes, mySalary will have been incremented by 5000. You can perform this kind of assignment with any mathematical operator:

mySalary = mySalary * 5000;
mySalary = mySalary - 5000;

and so forth.

The need to perform this kind of manipulation is so common that C# includes special operators for self-assignment. Among these operators are +=, -=, *=, /=, and %=, which, respectively, combine addition, subtraction, multiplication, division, and modulus, with self-assignment. Thus, you can write the previous examples as:

mySalary += 5000;
mySalary *= 5000;
mySalary -= 5000;

These three instructions, respectively, increment mySalary by 5000, multiply mySalary by 5000, and subtract 5000 from the mySalary variable.

Increment or Decrement by 1

Because incrementing and decrementing by exactly 1 is a very common need, C# provides two additional special operators for these purposes: increment (++) and decrement (--).

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.