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

CSharp Bible (2002) [eng]-1

.pdf
Скачиваний:
42
Добавлен:
16.08.2013
Размер:
4.29 Mб
Скачать

Chapter 8, you will find that your classes can redefine some of these operators. This is called operator overloading, and it enables you to redefine how the operators calculate their results.

Chapter 5: Controlling the Flow of Your

Code

In This Chapter

The behavior of your C# code often depends on conditions that are determined at runtime. You may want to write an application that greets its users with a message of "Good morning" if the current time is before 12:00 P.M., for example; or "Good afternoon" if the current time is between 12:00 P.M. and 6:00 P.M.

Behavior like this requires that your C# code examine values at runtime and take an action based on the values. C# supports a variety of code constructs that enable you to examine variables and perform one or many actions based upon those variables. This chapter looks at the C# flow control statements that will act as the brains for the applications you write.

Statements in C#

A statement is a valid C# expression that defines an action taken by your code. Statements can examine variable values, set new values into a variable, call methods, perform an operation, create objects, or take some other action.

The shortest possible statement in C# is the empty statement. The empty statement consists of only the semicolon:

;

You can use the empty statement to say, "Do nothing here." This may not seem too useful, but it does have its place.

Note All statements in C# end with a semicolon.

Statements are grouped into statement lists. Statement lists consist of one or more statements written in sequence:

int MyVariable;

MyVariable = 123;

MyVariable += 234;

Usually, statements are written on their own line. However, C# does not require this layout. C# ignores any whitespace between statements and accepts any layout as long as each statement is separated by a semicolon:

int MyVariable;

MyVariable = 123; MyVariable += 234;

Statement lists are enclosed in curly brackets. A statement list enclosed in curly brackets is called a statement block. You use statement blocks most often when you write code for a function. The entire statement list for the function is enclosed in a statement block. It is perfectly legal to use only one statement in a statement block:

public static void Main()

{

System.Console.WriteLine("Hello!");

}

C# does not impose any limit on the number of statements that you can place in a statement block.

Using statements to delcare local variables

Declaration statements declare local variables in your code. You've seen many examples of this kind of statement already. Declaration statements specify a type and a name for a local variable:

int MyVariable;

You can also initialize the variable when you declare it by using an equals sign and assigning a value to the variable:

int MyVariable = 123;

C# allows you to list multiple variables in the same statement. Use commas to separate the variable names:

int MyFirstVariable, MySecondVariable;

Each variable in the statement has the specified type. In the preceding example, both the MyFirstVariable and MySecondVariable are of type int.

Constant declarations define a variable whose value cannot change during the execution of the code. Constant declarations use the C# keyword const and must assign a value to the variable when the variable is declared:

const int MyVariable = 123;

The benefits of constant declarations include readability and code management. You may have constant values in your code, and assigning them names makes your code more readable than if their value were used. In addition, using values throughout your code poses a tedious task should these values need to be changed. When a constant is used, you need to change only one line of code. For example, suppose you're writing code for an application that performs geometric measurements. One of the values that you'll want to work with is pi, the ratio of a circle's circumference to its diameter. Without a constant declaration, you may be writing code like the following:

Area = 3.14159 * Radius * Radius;

Using a constant expression makes the code a bit easier to understand:

const double Pi = 3.14159;

Area = Pi * Radius * Radius;

This is especially useful if you're using the value of pi many times in your code.

Using selection statements to select your code's path

Selection statements select one of several possible code paths for execution. The selected code path is based on the value of an expression.

The if statement

The if statement works with an expression that evaluates to a Boolean value. If the Boolean expression evaluates to true, the statement embedded in the if statement is executed. If the Boolean expression evaluates to false, the statement embedded in the if statement is not executed:

if(MyVariable == 123) System.Console.WriteLine("MyVariable's value is 123.");

The Boolean expression is enclosed in parentheses. The embedded statement follows the parentheses. A semicolon is used to close the embedded statement, but not the Boolean expression.

Note When you use the if statement to check for equality, you must always use two equals signs. Two equals signs check for equality, whereas one equals sign performs an assignment. If you accidentally use one equals sign within an if statement, the if statement will always return a true condition.

In the preceding example, the value of MyVariable is compared to the literal value 123. If the value is equal to 123, the expression evaluates to true and the message MyVariable's value is 123. is written to the console. If the value is not equal to 123, the expression evaluates to false and nothing is printed to the console.

The if statement can be followed by an else clause. The else keyword is followed by an embedded statement that is executed if the Boolean expression used in the if clause evaluates to false:

if(MyVariable == 123) System.Console.WriteLine("MyVariable's value is 123.");

else

System.Console.WriteLine("MyVariable's value is not 123.");

In the preceding example, the value of MyVariable is compared to the literal value 123. If the value is equal to 123, the expression evaluates to true and the message MyVariable's value is 123. is written to the console. If the value is not equal to 123, the expression evaluates to false and the message MyVariable's value is not 123. is written to the console.

The else clause can be followed by an if clause of its own:

if(MyVariable == 123) System.Console.WriteLine("MyVariable's value is 123.");

else if(MyVariable == 124) System.Console.WriteLine("MyVariable's value is 124.");

else

System.Console.WriteLine("MyVariable's value is not 123.");

The if and else clauses enable you to associate a statement with the clause. Ordinarily, C# enables you to associate only a single statement with the clause, as shown in the following code:

if(MyVariable == 123) System.Console.WriteLine("MyVariable's value is 123.");

System.Console.WriteLine("This always prints.");

The statement that writes This always prints. to the console always executes. It does not belong to the if clause and executes regardless of whether the value of MyVariable is 123. The only statement that is dependent on the comparison of MyVariable to 123 is the statement that writes MyVariable's value is 123. to the console. If you want to associate multiple statements with an if clause, use a statement block:

if(MyVariable == 123)

{

System.Console.WriteLine("MyVariable's value is 123."); System.Console.WriteLine("This prints if MyVariable == 123.");

}

You can also use statement blocks in else clauses:

if(MyVariable == 123)

{

System.Console.WriteLine("MyVariable's value is 123."); System.Console.WriteLine("This prints if MyVariable == 123.");

}

else

{

System.Console.WriteLine("MyVariable's value is not 123."); System.Console.WriteLine("This prints if MyVariable != 123.");

}

Because statement blocks can enclose a single statement, the following code is also legal:

if(MyVariable == 123)

{

System.Console.WriteLine("MyVariable's value is 123.");

}

The switch statement

The switch statement evaluates an expression and compares the expression's value to a variety of cases. Each case is associated with a statement list, called a switch section. C# executes the statement list associated with the switch section matching the expression's value.

The expression used as the driver for the switch statement is enclosed in parentheses that follow the switch keyword. Curly brackets follow the expression, and the switch sections are enclosed in the curly brackets:

switch(MyVariable)

{

// switch sections are placed here

}

The expression used in the switch statement must evaluate to one of the following types:

sbyte

byte

short

ushort

int

uint

long

ulong

char

string

You can also use an expression whose value can be implicitly converted to one of the types in the preceding list.

Switch sections start with the C# keyword case, which is followed by a constant expression. A colon follows the constant expression, and the statement list follows the colon:

switch(MyVariable)

{

case 123:

System.Console.WriteLine("MyVariable == 123"); break;

}

The break keyword signals the end of your statement block.

C# evaluates the expression in the switch statement and then looks for a switch block whose constant expression matches the expression's value. If C# can find a matching value in one of the switch sections, the statement list for the switch section executes.

A switch statement can include many switch sections, each having a different case:

switch(MyVariable)

{

case 123:

System.Console.WriteLine("MyVariable == 123"); break;

case 124:

System.Console.WriteLine("MyVariable == 124"); break;

case 125:

System.Console.WriteLine("MyVariable == 125"); break;

}

C# enables you to group multiple case labels together. If you have more than one case that needs to execute the same statement list, you can combine the case labels:

switch(MyVariable)

{

case 123: case 124:

System.Console.WriteLine("MyVariable == 123 or 124"); break;

case 125:

System.Console.WriteLine("MyVariable == 125"); break;

}

One of the case labels can be the C# keyword default. The default label can include its own statement list:

switch(MyVariable)

{

case 123:

System.Console.WriteLine("MyVariable == 123"); break;

default:

System.Console.WriteLine("MyVariable != 123"); break;

}

The default statement list executes when none of the other switch sections define constants that match the switch expression. The default statement list is the catchall that says, "If you can't find a matching switch block, execute this default code." Using the default keyword is optional in your switch statements.

Using iteration statements to execute embedded statements

Iteration statements execute embedded statements multiple times. The expression associated with the iteration statements controls the number of times that an embedded statement executes.

The while statement

The while statement executes an embedded statement list as long as the while expression evaluates to true. The Boolean expression that controls the while statement is enclosed in parentheses that follow the while keyword. The statements to be executed while the Boolean expression evaluates to true follow the parentheses:

int MyVariable = 0;

while(MyVariable < 10)

{

System.Console.WriteLine(MyVariable);

MyVariable++;

}

This code prints the following to the console:

0

1

2

3

4

5

6

7

8

9

The code embedded in the while statement continues to be executed as long as the value of MyVariable is less than 10. The embedded statements print the value of MyVariable to the console and then increment its value. When the value of MyVariable reaches 10, the Boolean expression MyVariable < 10 evaluates to false and the statement list embedded in the while statement no longer executes. The statement following the while statement is executed as soon as the while statement's Boolean expression evaluates to false.

The do statement

The while statement executes its embedded statements zero or more times. If the Boolean expression used in the while statement evaluates to false, none of the embedded statements execute:

int MyVariable = 100;

while(MyVariable < 10)

{

System.Console.WriteLine(MyVariable);

MyVariable++;

}

This code does not print anything to the console because the Boolean expression used in the while statement, MyVariable < 10, evaluates to false the first time it executes. Because the Boolean expression evaluates to false right away, the embedded statements are never executed.

If you want to ensure that the embedded statements are executed at least once, you can use a do statement. The do statement is followed by embedded statements, which are followed by a while keyword. The Boolean expression that controls the number of times that the loop executes follows the while keyword:

int MyVariable = 0;

do

{

System.Console.WriteLine(MyVariable);

MyVariable++;

}

while(MyVariable < 10);

This code prints the following to the console:

0

1

2

3

4

5

6

7

8

9

The embedded statements always execute at least once, because the Boolean expression is evaluated after the embedded statements execute, as shown in the following code:

int MyVariable = 100;

do

{

System.Console.WriteLine(MyVariable);

MyVariable++;

}

while(MyVariable < 10);

This code prints the following to the console:

100

The for statement

The for statement is the most powerful of the iteration statements. The control code in a for statement is in three parts:

An initializer, which sets the starting conditions of the for statement loop

A condition, which specifies the Boolean expression that keeps the for statement executing

An iterator, which specifies statements that are executed at the end of every pass through the embedded statements

The for statement begins with the for keyword, followed by parentheses. The parentheses contain the initializer, the condition, and the iterator statements, all separated by semicolons. The embedded statements follow the parentheses.

Take a look at the following simple for loop:

int MyVariable;

for(MyVariable = 0; MyVariable < 10; MyVariable++)

{

System.Console.WriteLine(MyVariable);

}

The initializer in this for loop is the statement MyVariable = 0. The initializer executes only once in a for loop and executes before the embedded statements execute for the first time.

The condition in this for loop is the statement MyVariable < 10. The condition in a for loop must be a Boolean expression. The embedded statements in a for loop are executed as long as this Boolean expression evaluates to true. When the expression evaluates to false, the embedded statements no longer execute.

The iterator in this for loop is the statement MyVariable++. The iterator executes after each pass through the embedded statements in the for loop.

When you put all this information together, you can read the for statement as follows: "Set MyVariable equal to zero. As long as the value of MyVariable is less than 10, write the value to the console and then increment the value of MyVariable". These instructions print the following to the console:

0

1

2

3

4

5

6

7

8

9

The initializer, the condition, and the iterator in a for loop are all optional. If you choose not to use one of the parts, just write a semicolon without specifying the statement. The following code is logically equivalent to the preceding code:

int MyVariable = 0;

for(; MyVariable < 10; MyVariable++)

{

System.Console.WriteLine(MyVariable);

}

This code is also equivalent to the original code:

int MyVariable;

for(MyVariable = 0; MyVariable < 10; )

{

System.Console.WriteLine(MyVariable);

MyVariable++;

}

Use caution when omitting the condition section of the for loop. The following code illustrates the problems that can arise from leaving out conditions:

int MyVariable;

for(MyVariable = 0; ; MyVariable++)

{

System.Console.WriteLine(MyVariable);

}

This code runs until MyVariable eventually causes an error because it contains a number too large to store. This occurs because no condition in the for loop eventually evaluates to false, which allows the variable to increment until it exceeds its limitations. Missing conditions evaluate to true in a for loop. Because the condition in the preceding code example is always true, it never evaluates to false and the for statement never stops executing its embedded statement.

The initializer, condition, and iterator expressions can contain multiple statements, separated by commas. The following code is legal:

int MyFirstVariable; int MySecondVariable;

for(MyFirstVariable = 0, MySecondVariable = 0; MyFirstVariable < 10;

MyFirstVariable++, MySecondVariable++)

{

System.Console.WriteLine(MyFirstVariable);

System.Console.WriteLine(MySecondVariable);

}

The foreach statement

You can use the foreach statement to iterate over the elements in a collection. Arrays in C# support the foreach statement, and you can use the foreach statement to work easily with each element in the array.

Use the foreach statement by typing the foreach keyword, followed by paren-theses. The parentheses must contain the following information:

The type of the element in the collection

An identifier name for an element in the collection

The keyword in

The identifier of the collection

Embedded statements follow the parentheses.

Listing 5-1 shows the foreach statement in action. It creates a five-element integer array and then uses the foreach statement to visit each element in the array and write its value to the console.

Listing 5-1: Using the foreach Statement

class Listing5_1

{

public static void Main()

{

int [] MyArray;

MyArray = new int [5];

MyArray[0] = 0;

MyArray[1] = 1;

MyArray[2] = 2;

MyArray[3] = 3;

Соседние файлы в предмете Программирование на C++