Chapter 4. Operators

An operator is a symbol (such as =, +, or >) that causes C# to take an action. That action might be an assignment of a value to a variable, the addition of two values, a comparison of two values, and so forth.

In the previous chapter, you saw the assignment operator used. The single equals sign (=) is used to assign a value to a variable; in this case, the value 15 to the variable myVariable:

    myVariable = 15;

C# has many different operators that you’ll learn about in this chapter. There’s a full set of mathematical operators, and a related set of operators just for incrementing and decrementing in integral values by one, which actually are quite useful for controlling loops, as you’ll see in Chapter 5. There are also operators available for comparing two values, which are used in the branching statements, as I’ll demonstrate in the next chapter.

The Assignment Operator (=)

The assignment operator causes the operand on the left side of the operator to have its value changed to whatever is on the right side of the operator. The following expression assigns the value 15 to myVariable:

    myVariable = 15;

The assignment operator also allows you to chain assignments, assigning the same value to multiple variables, as follows:

    myOtherVariable = myVariable = 15;

The previous statement assigns 15 to myVariable, and then also assigns the value (15) to myOtherVariable. This works because the statement:

    myVariable = 15;

is an expression; it evaluates to the value assigned. That is, the expression:

    myVariable = 15;

itself evaluates to 15, and it is this value (15) that is then assigned to myOtherVariable.

C# uses five mathematical operators : four for standard calculations and one to return the remainder when dividing integers. The following sections consider the use of these operators.

C# provides a special operator, modulus (%), to retrieve the remainder from integer division. For example, the statement 17%4 returns 1 (the remainder after integer division).

Example 4-2 demonstrates the effect of division on integers, floats, doubles, and decimals.

The output looks like this:

    Integer:            4
    float:              4.25
    double:             4.25
    decimal:            4.25

    Remainder(modulus) from integer division:         1

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. C# provides several operators for these calculations.

To complicate matters further, you might want to increment a variable and assign the results to a second variable:

    resultingValue = originalValue++;

The question arises: 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. The semantics of the prefix increment operator is “increment the original value and then assign the incremented value to result” while the semantics of the postfix increment operator is “assign the original value to result, and then increment original.”

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.

The output looks like this:

    After prefix: 11, 11
    After postfix: 12, 11

The prefix and postfix operators can be applied, with the same logic, to the decrement operators, as shown in Example 4-4. Again, note the output.

The output looks like this:

    After prefix: 9, 9
    After postfix: 8, 9

Relational operators compare two values and then return a Boolean value (true or false). The greater than operator (>), for example, returns true if the value on the left of the operator is greater than the value on the right. Thus, 5>2 returns the value true, while 2>5 returns the value false.

The relational operators for C# are shown in Table 4-1. This table assumes two variables: bigValue and smallValue, in which bigValue has been assigned the value 100, and smallValue the value 50.

Each of these relational operators acts as you might expect. Notice that most of these operators are composed of two characters. For example, the greater than or equal to operator (>=) is created with the greater than symbol (>) and the equals sign (=). Notice also that the equals operator is created with two equals signs (==) because the single equals sign alone (=) is reserved for the assignment operator.

The C# equals operator (==) tests for equality between the objects on either side of the operator. This operator evaluates to a Boolean value (true or false). Thus, the statement:

    myX == 5;

evaluates to true if and only if the myX variable has a value of 5.

Use of Logical Operators with Conditionals

As you program, you’ll often want to test whether a condition is true; for example, using the if statement, which you’ll see in the next chapter. Often you will want to test whether two conditions are both true, only one is true, or neither is true. C# provides a set of logical operators for this, shown in Table 4-2.

The examples in this table assume two variables, x and y, in which x has the value 5 and y has the value 7.

The and operator tests whether two statements are both true. The first line in Table 4-2 includes an example that illustrates the use of the and operator:

    (x == 3) && (y == 7)

The entire expression evaluates false because one side (x == 3) is false. (Remember that x has the value 5 and y has the value 7.)

With the or operator, either or both sides must be true; the expression is false only if both sides are false. So, in the case of the example in Table 4-2:

    (x == 3) || (y == 7)

the entire expression evaluates true because one side (y==7) is true.

With a not operator, the statement is true if the expression is false, and vice versa. So, in the accompanying example:

    ! (x == 3)

the entire expression is true because the tested expression (x==3) is false. (The logic is: “it is true that it is not true that x is equal to 3.”)

Operator Precedence

The compiler must know the order in which to evaluate a series of operators. For example, if I write:

    myVariable = 5 + 7 * 3;

there are three operators for the compiler to evaluate (=, +, and *). It could, for example, operate left to right, which would assign the value 5 to myVariable, then add 7 to the 5 (12) and multiply by 3 (36)—but of course, then it would throw that 36 away. This is clearly not what is intended.

The rules of precedence tell the compiler which operators to evaluate first. As is the case in algebra, multiplication has higher precedence than addition, so 5+7*3 is equal to 26 rather than 36. Both addition and multiplication have higher precedence than assignment, so the compiler will do the math and then assign the result (26) to myVariable only after the math is completed.

In C#, parentheses are also used to change the order of precedence much as they are in algebra. Thus, you can change the result by writing:

    myVariable = (5+7) * 3;

Grouping the elements of the assignment in this way causes the compiler to add 5+7, multiply the result by 3, and then assign that value (36) to myVariable.

Table 4-3 summarizes operator precedence in C#, using x and y as possible terms to be operated upon.[1]

The operators are listed in precedence order according to the category in which they fit. That is, the primary operators (such as x++) are evaluated before the unary operators (such as !). Multiplication is evaluated before addition.

In some complex equations, you might need to nest parentheses to ensure the proper order of operations. For example, assume I want to know how many seconds my family wastes each morning. The adults spend 20 minutes over coffee each morning and 10 minutes reading the newspaper. The children waste 30 minutes dawdling and 10 minutes arguing.

Here’s my algorithm:

    (((minDrinkingCoffee + minReadingNewspaper )* numAdults ) +
    ((minDawdling + minArguing) * numChildren)) * secondsPerMinute.

Although this works, it is hard to read and hard to get right. It’s much easier to use interim variables:

    wastedByEachAdult = minDrinkingCoffee + minReadingNewspaper;
    wastedByAllAdults = wastedByEachAdult * numAdults;
    wastedByEachKid = minDawdling + minArguing;
    wastedByAllKids = wastedByEachKid * numChildren;
    wastedByFamily = wastedByAllAdults + wastedByAllKids;
    totalSeconds = wastedByFamily * 60;

The latter example uses many more interim variables, but it is far easier to read, understand, and (most importantly) debug. As you step through this program in your debugger, you can see the interim values and make sure they are correct. See Chapter 9 for more information.

Summary

  • An operator is a symbol that causes C# to take an action.

  • The assignment operator (=) assigns a value to an object or variable.

  • C# includes four simple arithmetic operators: +, -, *, and /, and numerous variations such as +=, which increments a variable on the left side of the operator by the value on the right side.

  • When you divide integers, C# discards any fractional remainder.

  • The modulus operator (%) returns the remainder from integer division.

  • C# includes numerous special operators such as the self-increment (++) and self-decrement (—) operators.

  • To increment a value before assigning it, you use the prefix operator (++x); to increment the value after assigning it, use the postfix operator (x++).

  • The relational operators compare two values and return a Boolean. These operators are often used in conditional statements.

  • The conditional operator (?:) is the one ternary operator found in C#. It invokes the expression to the left of the colon if the tested condition evaluates true, and the expression to the right of the colon if the tested condition evaluates false.

  • The compiler evaluates operators according to a series of precedence rules, and parentheses have the “highest” precedence.

  • It is good programming practice to use parentheses to make your order of precedence explicit if there may be any ambiguity.

Quiz



[1] This table includes operators that are so esoteric as to be beyond the scope of this book. For a fuller explanation of each, please see Programming C#, Fourth Edition, by Jesse Liberty (O’Reilly, 2005).