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

C H A P T E R 8

Expressions and Operators

Expressions

Literals

Order of Evaluation

Simple Arithmetic Operators

The Remainder Operator

Relational and Equality Comparison Operators

Increment and Decrement Operators

Conditional Logical Operators

Logical Operators

Shift Operators

Assignment Operators

The Conditional Operator

Unary Arithmetic Operators

User-Defined Type Conversions

Operator Overloading

The typeof Operator

Other Operators

201

CHAPTER 8 EXPRESSIONS AND OPERATORS

Expressions

This chapter defines expressions and describes the operators provided by C#. It also explains how you can define the C# operators to work with your user-defined classes.

An expression is a string of operators and operands. The following are some of the constructs that can act as operands:

Literals

Constants

Variables

Method calls

Element accessors, such as array accessors and indexers

Other expressions

The C# operators take one, two, or three operands. An operator does the following:

Takes its operands as input

Performs an action

Returns a value, based on the action

Expressions can be combined, using operators, to create other expressions, as shown in this expression, with three operators and four operands:

Evaluating an expression is the process of applying each operator to its operands, in the proper sequence, to produce a value.

The value is returned to the position at which the expression was evaluated. There, it might in turn be an operand in an enclosing expression.

Besides the value returned, some expressions also have side effects, such as setting a value in memory.

202

CHAPTER 8 EXPRESSIONS AND OPERATORS

Literals

Literals are numbers or strings typed into the source code that represent a specific, set value of a specific type.

For example, the following code shows literals of six types. Notice, for example, the difference between the double literal and the float literal.

static void Main()

Literals

 

{

 

Console.WriteLine("{0}", 1024);

// int literal

Console.WriteLine("{0}", 3.1416);

// double literal

Console.WriteLine("{0}", 3.1416F);

// float literal

Console.WriteLine("{0}", true);

// boolean literal

Console.WriteLine("{0}", 'x');

// character literal

Console.WriteLine("{0}", "Hi there");

// string literal

}

 

 

The output of this code is the following:

1024

3.1416

3.1416 True

x

Hi there

Because literals are written into the source code, their values must be known at compile time. Several of the predefined types have their own forms of literal:

Type bool has two literals: true and false.

For reference type variables, literal null means that the variable is not set to a reference in memory.

203

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