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.

Tip

It is important not to confuse the assignment operator (=) with the equality, or equals, operator (==), which has two equals signs and is described later in the chapter. The assignment operator does not test for equality; it assigns a value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset