Книга: C# 2008 Programmer

switch Statement

switch Statement

You can evaluate multiple expressions and conditionally execute blocks of code by using if-else statements. Consider the following example:

string symbol = "YHOO";
if (symbol == "MSFT") {
 Console.WriteLine(27.96);
} else if (symbol == "GOOG") {
 Console.WriteLine(437.55);
} else if (symbol == "YHOO") {
 Console.WriteLine(27.15);
} else Console.WriteLine("Stock symbol not recognized");

One problem with this is that multiple if and else-if conditions make the code unwieldy — and this gets worse when you have lots of conditions to check. A better way would be to use the switch keyword:

switch (symbol) {
case "MSFT":
 Console.WriteLine(27.96);
 break;
case "GOOG":
 Console.WriteLine(437.55);
 break;
case "YHOO":
 Console.WriteLine(27.15);
 break;
default:
 Console.WriteLine("Stock symbol not recognized");
 break;
}

The switch keyword handles multiple selections and uses the case keyword to match the condition. Each case statement must contain a unique value and the statement, or statements, that follow it is the block to execute. Each case statement must end with a break keyword to jump out of the switch block. The default keyword defines the block that will be executed if none of the preceding conditions is met.

The following example shows multiple statements in a case statement:

string symbol = "MSFT";
switch (symbol) {
case "MSFT":
 Console.Write("Stock price for MSFT: ");
 Console.WriteLine(27.96);
 break;
case "GOOG":
 Console.Write("Stock price for GOOG: ");
 Console.WriteLine(437.55);
 break;
case "YHOO":
 Console.Write("Stock price for YHOO: ");
 Console.WriteLine(27.15);
 break;
default:
 Console.WriteLine("Stock symbol not recognized");
 break;
}

In C#, fall-throughs are not allowed; that is, each case block of code must include the break keyword so that execution can be transferred out of the switch block (and not "fall through" the rest of the case statements). However, there is one exception to this rule — when a case block is empty. Here's an example:

string symbol = "INTC";
switch (symbol) {
case "MSFT":
 Console.WriteLine(27.96);
 break;
case "GOOG":
 Console.WriteLine(437.55);
 break;
case "INTC":
case "YHOO":
 Console.WriteLine(27.15);
 break;
default:
 Console.WriteLine("Stock symbol not recognized");
 break;
}

The case for "INTC" has no execution block/statement and hence the execution will fall through into the case for "YHOO", which will incorrectly print the output "27.15". In this case, you need to insert a break statement after the "INTC" case to prevent the fall-through:

switch (symbol) {
case "MSFT":
 Console.WriteLine(27.96);
 break;
case "GOOG":
 Console.WriteLine(437.55);
 break;
case "INTC":
 break;
case "YHOO":
 Console.WriteLine(27.15);
 break;
default:
 Console.WriteLine("Stock symbol not recognized");
 break;
}

Оглавление книги

Оглавление статьи/книги

Генерация: 0.733. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз