You’ll often find yourself needing to manipulate the value in a variable, and then store that result back in the original variable. Suppose, for example, that you have a variable inventory
, which you use to keep track of the quantity of widgets you have in your warehouse. You wouldn’t want to have to create new variables every time inventory increases or decreases; you want the current value to always be available in inventory
. C# provides several operators for just these kinds of calculations.
Suppose you want to increase the mySalary
variable by 5,000 (congratulations on your raise!). You can do this by writing:
mySalary = mySalary + 5000;
In simple arithmetic, this would make no sense, but that’s because it’s not an equation, it’s a C# assignment expression. In C#, this line means “add 5,000 to the value in mySalary
, and assign the sum back to mySalary
.” Thus, after this operation completes, mySalary
will have been incremented by 5,000. You can perform this kind of assignment with any mathematical operator:
mySalary = mySalary * 5000; mySalary = mySalary - 5000;
The need to perform this kind of manipulation is so common that C# includes special operators for self-assignment. These operators are +=, -=, *=, /=
, and %=
, which, respectively, combine addition, subtraction, multiplication, division, and modulus with self-assignment. Thus, you can write the previous three examples as:
mySalary += 5000; mySalary *= 5000; mySalary -= 5000;
These three instructions, respectively, increment mySalary
by 5,000, multiply mySalary
by 5,000, and subtract 5,000 from the mySalary
variable.
You may have noticed from the preceding section that C# developers like to save keystrokes. Another mathematical operation you’ll use a lot is incrementing and decrementing by exactly 1. You’ll find that you need counters of all sorts, starting with loop controllers in Chapter 5. C# provides two additional special operators for these purposes: increment (++
) and decrement (--
).
So, if you want to increment the variable myAge
by 1, you can write:
myAge++;
This is equivalent to writing either of the following:
myAge = myAge + 1; myAge += 1;
To complicate matters further, you might want to increment a variable and assign the results to a second variable:
resultingValue = originalValue++;
That raises a question: do you want to assign before you increment the value, or after? In other words, if originalValue
starts out with the value 10, do you want to end with both resultingValue
and originalValue
equal to 11, or do you want resultingValue
to be equal to 10 (the original value) and originalValue
to be equal to 11?
C# offers two specialized ways to use the increment and decrement operators: prefix and postfix. The way you use the ++
operator determines the order in which the increment/decrement and assignment take place.
To use the prefix operator to increment, place the ++
symbol before the variable name; to use the postfix operator to increment, place the ++
symbol after the variable name:
result =++
original; // prefix result = original++
; // postfix
It is important to understand the different effects of prefix and postfix, as illustrated in Example 4-3. Note the output.
Example 4-3. The prefix and postfix operators behave slightly differently; the prefix operator increments before you assign; the postfix operator assigns, then increments
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_4_3_ _ _ _Prefix_and_Postfix { class Program { static void Main( ) { int original = 10; int result; // increment then assign result = ++original; Console.WriteLine("After prefix: {0}, {1}", original, result); // assign then increment result = original++; Console.WriteLine("After postfix: {0}, {1}", original, result); } } }
After prefix: 11, 11 After postfix: 12, 11
Look at the prefix increment from Example 4-3 again:
result = ++original;
The semantics of the prefix increment operator are “increment the value of original
and then assign the incremented value to result
.” So, original
starts with a value of 10, you increment that to 11, and assign it to result
. In the end, both variables have the value of 11.
Now look at the postfix increment:
result = original++;
The semantics here are “assign the value of original
to result
, and then increment original
.” The value of original
is 11 at this point, which gets assigned to result
, and then original
is incremented.
The prefix and postfix operators work the same way with the decrement operators, for the same reasons, as shown in Example 4-4. Again, note the output.
Example 4-4. Decrementing with the prefix and postfix operators works the same as incrementing
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_4_4_ _ _ _Decrement_Operators { using System; class Program { static void Main( ) { int original = 10; int result; // increment then assign result = --original; Console.WriteLine("After prefix: {0}, {1}", original, result); // assign then increment result = original--; Console.WriteLine("After postfix: {0}, {1}", original, result); } } }
After prefix: 9, 9 After postfix: 8, 9
The increment operators are meant to be a convenient shortcut to save you keystrokes, and as you go through this book, you’ll see them used in various common ways, such as controlling loops. Remember, though, that one of the goals of good programming is readability. If you overuse the prefix and postfix operators in an attempt to be efficient with your typing, but six months from now you’re trying to puzzle out what your code does and how, you haven’t really saved any time. If you think that using these operators will make your code confusing, go ahead and write out the expression the long way. You may thank yourself later.
Get Learning C# 3.0 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.