Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Premier Press - C# Professional Projects

.pdf
Скачиваний:
475
Добавлен:
12.02.2016
Размер:
14.7 Mб
Скачать

28

Part I

INTRODUCTION TO C#

 

 

 

Statements and Expressions

Statements in C# are similar to those in C and C++. Statements in C# can be of two types:

Simple

 

 

 

Embedded

 

 

Y

 

 

 

Simple statements include all variable declaration statements and labeled state-

 

 

L

ments. However, all other statements that are embedded and are a part of another

statement are called embedded statements. All statements in C# are enclosed within

curly braces {}.

 

M

 

 

 

 

Types of Statements

A

 

 

F

E

 

C# supports simple statements and embedded statements, such as selection, itera-

T

 

 

tion, and jump statements. Look at these statements in detail.

Simple Statements

Simple statements include all declaration and labeled statements. Simple statements also include statements that are used to call methods.

Declaration Statements

A declaration statement is used to declare a variable or a constant. You can use a single statement to declare more than one variable or constant. The following is an example of an initializing statement.

public int i, y;

i = 45;

y = 37;

Similarly, you use declaration statements to declare constants. Constants are data types whose value cannot be changed after being declared. The const keyword is used to declare a constant. Consider the following code sample:

const char x = a;

The previous code declares a constant x of the type character and assigns a value a to it.The value of the constant x cannot be changed throughout the lifetime of x.

Team-Fly®

C# BASICS

Chapter 2

29

 

 

 

Labeled Statements

In addition to declaring variables and constants, you can declare labels in C#. A labeled statement is a simple statement that is used to declare a label.The syntax of a labeled statement is as follows:

<label1> : <statement1>

Here, label1 is the name of a label and statement1 specifies the statements to be executed when the control reaches the label. You use a goto statement to refer to a label.

Method Call Statements

A method call statement is also a type of a simple statement. A method call statement is used to call a method that is already created. The following code sample is an example of a method call statement:

public int x;

x = 100;

MessageBox.Show (x);

The previous code calls the Show method of the class MessageBox.

Selection Statements

C# also provides you with selection statements. In cases where the program has to execute one block of statements out of all the available blocks of statements, selection statements are used. In such a case, the program code needs to select the block of statements to be executed, which are therefore called selection statements. The selection of the statements to be executed is based on the value returned by evaluating an expression that follows the selection statement. The selection statements are of two types:

if-statement

switch-statement

if-statement

The if-statement is a decision-making statement that selects a specific set of statements to execute.The selection of the set of statements is based on a Boolean value

30

Part I

INTRODUCTION TO C#

 

 

 

that is returned by evaluating a given expression. The syntax of an if-statement is as follows:

if (Boolean-expression) statement1

The Boolean expression returns a value of either true or false. If the Boolean expression evaluates to true, the statement following the Boolean expression is executed. After the execution of statement1, the control passes to the end of the if-statement. If the result of the Boolean expression is false, the statements in the else block are executed.

Look at the following example of an if-else statement:

int x;

if (x >= 0)

{

MessageBox.Show(“x is a positive number.”);

}

else

{

MessageBox.Show(“x is a negative number.”);

}

The previous code tests for the value of x, and if the Boolean expression evaluates to true, the message “x is a positive number.” is displayed.However, if the value of the Boolean expression (x >= 0) is false, the message “x is a negative number.” is displayed.

If an else statement is not provided in the if-statement, the control is transferred to the end of the if-statement when the result of the Boolean expression is false.

switch-statement

Similar to the if-statement, the switch-statement is a type of a selection statement. However, a switch-statement is used when there are multiple block statements from which to choose. The syntax of a switch-statement is as follows:

--------------

switch (expression)

{

case constant-expression:

statement

C# BASICS

Chapter 2

31

 

 

 

jump-statement [default:

statement jump-statement]

}

--------------

The switch statement is written with a switch keyword, followed by an expression to be evaluated.The switch statement evaluates an expression, and the set of statements to be executed is selected.The selection is based on the result of the expression. The different sets of statements to be executed are considered as different cases. The case keyword is used to define different cases. The result of the statement is matched to the available cases, and the set of statements to be executed is selected. The following is an example of a switch-statement:

int x; switch (x)

{

case 1:

MessageBox.Show(“x is a positive number.”); break;

case 2:

MessageBox.Show(“x is a negative number.”); break;

default:

MessageBox.Show(“x is equal to 0.”); break;

}

As shown in the preceding code, you can also include a default case. The default case is executed if the result of the expression does not match any of the available cases. A break statement is used to pass the control out of the case.

In C and C++, a fall-through condition can occur. In a fall-through condition, if you omit any of the break statements, the program executes two cases. However, in C#, a fall-through condition is omitted because the compiler throws an error for each case that does not end with a break statement.The following code in C# generates an error:

int x;

switch (x)

32

Part I

INTRODUCTION TO C#

 

 

 

{

case 1:

MessageBox.Show(“x is a positive number.”);

break;

case 2:

MessageBox.Show(“x is a negative number.”);

default:

MessageBox.Show(“x is equal to 0.”);

break;

}

If you need to execute two cases, you need to provide an explicit goto statement. The syntax for such a code is given as follows:

switch (expression)

{

case 1 : statement goto case2;

case 2 : statement

goto default; [default:

statement jump-statement]

}

In this case, the compiler first executes case1, then case2, and then the default case.

In addition to the selection statements, types of statements also include iteration statements.

Iteration Statements

The iteration statements are used to execute a set of statements repeatedly until a condition is met. The types of iteration statements are as follows:

for loop

foreach loop

C# BASICS

Chapter 2

33

 

 

 

while loop

do-while loop

for Loop

The for loop in C# is similar to the for loop in C and C++. The for loop is used to execute a given set of statements until a given expression in the for loop returns true. The syntax of a for loop is as follows:

for (initializer; condition; iterator)

{

-------------------

}

Here, initializer is an expression that is evaluated before the control enters the loop. The condition specifies the condition that is evaluated before every iteration is completed.The iterator is the expression that is evaluated after every iteration. The statements in the for loop are continuously executed until the expression returns false.

If you want to transfer the control of execution to the end of the for loop when the control is within the loop, you can use a break statement explicitly. In such a case, the statements within the for loop are not executed even if the condition evaluated is true. Therefore, the iteration stops.

However, if you need to end a particular iteration, you can use a continue statement.The control of execution passes to the end of the statements within the for loop, which ends only the running iteration.

foreach Loop

The foreach loop is introduced in C#. However, it did not exist in C and C++.The foreach loop in C# iterates the statements in the foreach loop for each element in an array or collection. The following example will help you to understand the

foreach loop.

int [] Integer = {15,89,1000,6} foreach (int x in Integer)

{

Console.WriteLine (x)

}

34

Part I

INTRODUCTION TO C#

 

 

 

Here, in is a keyword for the foreach loop.

TIP

The value of the variable in the foreach loop cannot change during the execution of the foreach loop.

while Loop

The while loop is similar to a for loop because it evaluates a condition and executes the statements within the while loop until the condition returns false. The while loop in C# is similar to the while loop in C and C++. If the condition that is evaluated results in false the first time, the while loop is not executed.The syntax of a while loop is similar to that of the for loop, except that the while loop takes only one parameter. The code sample that follows is an example of the while loop that is not executed.

int x = 20; while (x < 10)

{

Console.WriteLine (x);

x++;

}

When the code evaluates the condition for the first time, the result is false. Therefore, the control does not enter the loop.

do-while Loop

The do-while loop is another form of iteration statements in which the condition is evaluated for the first time after the statements in the do-while loop are executed. This implies that the do-while loop, in contrast to the while loop, is executed at least once. The following code executes the statements in the do-while loop once before it checks for the value of x and, therefore, displays the value of x once.

int x = 20; do {

Console.WriteLine (x); } while (x < 10)

C# BASICS

Chapter 2

35

 

 

 

Jump Statements

Jump statements are also a type of statement in C#.The jump statements are used to pass the control of the execution unconditionally to another line in the program. The line of code to which the control is transferred is called the target of the jump statement. The commonly used jump statements in C# are:

goto statement

return statement

break statement

continue statement

The jump statements in C# are similar to those in C and C++.

goto Statement

The goto statement is used to jump unconditionally to another line in a program. You need to specify the line to which the code jumps using a label. The syntax of the goto statement uses the goto keyword, such as:

goto Label1;

where Label1 specifies the line to which the code passes the control.

TIP

The goto statement cannot be used in the following cases:

Jumping into a block of code

Exiting a finally block

Jumping outside a class

return Statement

A return statement is another jump statement that is used to end a method of a class. After a method ends, the execution control is transferred to the calling method. If the method that includes the return statement has a return type, the

36

Part I

INTRODUCTION TO C#

 

 

 

method must a return a value of the return type. The syntax of the return statement is as follows:

return expression;

Here, return is a keyword that you use to write a return statement.

If the method is of the type void, the return statement does not take an expression.Constructors or destructors also do not require an expression with the return statement.

break Statement

As you have seen, you can use a return statement to end a method. Similarly, to end a loop, you use the break statement. It is used to exit from a loop, such as for, foreach, do, and do-while loop. The break statement passes the control out of the loop. The break statement is written using the break keyword.

break;

For nested loops, the break statement passes the control to the end of the innermost loop.

continue Statement

Similar to a break statement, the continue statement is also used with loops. The continue statement is used to end only the current iteration and not the entire loop. The execution again starts for the next iteration. The continue keyword is used to specify a continue statement.

continue;

A continue statement cannot be used to exit a finally block. You will learn about the finally block in Chapter 6, “Threads.”

Having learned about statements, you need to understand expressions. Expressions are also used to perform operations on variables.

Expressions

Expressions in C# are similar to that of C++. Expressions are defined as a sequence of operands and operators that are used to perform operations. An expression can

C# BASICS

Chapter 2

37

 

 

 

be of the following types: values, variables, classes, namespaces, indexers, and methods.

Operators

Operators are used to write expressions. Operators specify the kind of operation that is to be performed on the operands. The types of operators supported by C# are displayed in Table 2-3.

Table 2-3 The Types of Operators in C#

Types of Operators

Description

Unary operators

Unary operators perform operations on a single operand. For

 

example, the ++ and -- operators are unary operators. Unary oper-

 

ators can either precede or succeed the operand.Unary operators

 

are used with numeric data t ypes.

Binary operators

Binary operators perform operations on two operands. For exam-

 

ple, +, -, +=, -=,*, and / are binary operators. Binary operators are

 

written between the two operands.Binary operators are also used

 

with numeric operators.

Ternary operators

Ternary operators have three operands. C# supports only one

 

ternary operator, ? :.The ? : operator is equivalent to an if-else

 

statement.

 

 

Now look at the syntax of the ? : operator.

condition ? true value : false value

Here, condition is the condition of the if-else statement. It is a Boolean expression. If the condition evaluates to true, the true value is returned. Otherwise, the false value is returned.

The unary, binary, and ternary operators are further classified according to the operations they perform. Look at the operators supported by C# in detail.

The arithmetic operators are used to perform arithmetic operations. C# supports +, -, *, /, and %. These operators are similar to the operators in C++.

The increment and decrement operator increases or decreases the value of a variable by one. The increment operator is ++, and the decrement operator is --.