Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 8 EXPRESSIONS AND OPERATORS

Assignment Operators

The assignment operators evaluate the expression on the right side of the operator and use that value to set the variable expression on the left side of the operator. Table 8-14 lists the assignment operators.

The assignment operators are binary and right-associative.

Table 8-14. The Assignment Operators

Operator Description

=Simple assignment; evaluate the expression on the right, and assign the returned value to the variable or expression on the left.

*=

Compound assignment; var *= expr is equal to var = var * (expr).

/=

Compound assignment; var /= expr is equal to var = var / (expr).

%=

Compound assignment; var %= expr is equal to var= var % (expr).

+=

Compound assignment; var += expr is equal to var = var + (expr).

-=

Compound assignment; var -= expr is equal to var = var- (expr).

<<=

Compound assignment; var <<= expr is equal to var = var << (expr).

>>=

Compound assignment; var >>= expr is equal to var = var >> (expr).

&=

Compound assignment; var &= expr is equal to var = var & (expr).

^=

Compound assignment; var ^= expr is equal to var = var ^ (expr).

|=

Compound assignment; var |= expr is equal to var = var | (expr).

 

 

The syntax is as follows:

VariableExpression Operator Expression

225

CHAPTER 8 EXPRESSIONS AND OPERATORS

For simple assignment, the expression to the right of the operator is evaluated, and its value is assigned to the variable on the left.

int x; x = 5;

x = y * z;

The types of objects that can be on the left side of an assignment operator are the following. They are discussed later in the text.

Variables (local variables, fields, parameters)

Properties

Indexers

Events

Compound Assignment

Frequently, you’ll want to evaluate an expression and add the results to the current value of a variable, as shown here:

x = x + expr;

The compound assignment operators allow a shorthand method for avoiding the repetition of the left-side variable on the right side under certain common circumstances. For example, the following two statements are semantically equivalent, but the second is shorter and just as easy to understand.

x = x + (y – z); x += y – z;

The other compound assignment statements are analogous:

 

 

 

 

 

 

 

 

Notice the parentheses.

 

 

 

 

 

 

 

 

 

 

x

*=

y – z;

//

Equivalent

to

x

=

x

*

(y – z)

x

/=

y – z;

//

Equivalent

to

x

=

x

/

(y – z)

 

...

 

 

 

 

 

 

 

 

 

226

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]