Chapter 7. Operators

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

In the previous chapters, you’ve seen a number of operators at work. For example, in Chapter 5 you saw the assignment operator used. The single equal sign (=) is used to assign a value to a variable, in this case the value 15 to the variable myVariable:

myVariable = 15;

In Chapter 6 you saw more sophisticated operators, such as the greater-than comparison operator (>) used to compare two values:

if ( valueOne > valueTwo )

The preceding if statement compares valueOne with valueTwo; if the former is larger than the latter, the test evaluates true, and the if statement executes.

This chapter describes many of the operators used in C# in some detail.

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; ...

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.