Operators
An operator is a symbol that causes C# to take an action. The C# primitive types (e.g., int
) support a number of operators such as assignment, increment, and so forth.
The Assignment Operator (=)
The =
symbol 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. Statements that evaluate to a value are called expressions. You may be surprised how many statements do evaluate to a value. For example, an assignment such as:
myVariable = 57;
is an expression; it evaluates to the value assigned, which, in this case, is 57
.
Note that the preceding statement assigns the value 57
to the variable myVariable
. The assignment operator (=
) doesn't test equality; rather, it causes whatever is on the right side (57
) to be assigned to whatever is on the left side (myVariable
).
Warning
VB programmers take note: C# distinguishes between equality (two equals signs) and assignment (one equals sign).
Because myVariable = 57
(read aloud as "assign the numeric value 57 to the variable whose name is myVariable") is an expression that evaluates to 57
, it can be used as part of another assignment operator, such as:
mySecondVariable = myVariable = 57;
In this statement, the literal value 57
is assigned to the variable myVariable
. The value of that assignment (57
) is then assigned to the second variable, mySecondVariable
. Thus, the value 57
is assigned to both variables.
Tip
The value 57
is referred to as a literal value (as opposed to ...
Get Programming C# 3.0, 5th Edition 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.