The switch Statement


The second of C#’s selection statements is the switch. The switch provides for a multiway branch. Thus, it enables a program to select among several alternatives. Although a series of nested if statements can perform multiway tests, for many situations the switch is a more efficient approach. It works like this: The value of an expression is successively tested against a list of constants. When a match is found, the statement sequence associated with that match is executed. The general form of the switch statement is

 switch(expression) {   case constant1:      statement sequence      break;    case constant2:       statement sequence       break;    case constant3:      statement sequence      break;  .  .  .   default:      statement sequence      break; }

The switch expression must be of an integer type, such as char, byte, short, or int, or of type string (which is described later in this book). Thus, floating-point expressions, for example, are not allowed. Frequently, the expression controlling the switch is simply a variable. The case constants must be literals of a type compatible with the expression. No two case constants in the same switch can have identical values.

The default statement sequence is executed if no case constant matches the expression. The default is optional; if it is not present, no action takes place if all matches fail. When a match is found, the statements associated with that case are executed until the break is encountered.

The following program demonstrates the switch:

 // Demonstrate the switch. using System; class SwitchDemo {   public static void Main() {     int i;     for(i=0; i<10; i++)       switch(i) {         case 0:           Console.WriteLine("i is zero");           break;         case 1:           Console.WriteLine("i is one");           break;         case 2:           Console.WriteLine("i is two");           break;         case 3:           Console.WriteLine("i is three");           break;         case 4:           Console.WriteLine("i is four");           break;         default:           Console.WriteLine("i is five or more");           break;       }   } }

The output produced by this program is shown here:

 i is zero i is one i is two i is three i is four i is five or more i is five or more i is five or more i is five or more i is five or more

As you can see, each time through the loop, the statements associated with the case constant that matches i are executed. All others are bypassed. When i is five or greater, no case constants match, so the default statement is executed.

In the preceding example, the switch was controlled by an int variable. As explained, you can control a switch with any integer type, including char. Here is an example that uses a char expression and char case constants:

 // Use a char to control the switch. using System; class SwitchDemo2 {   public static void Main() {     char ch;     for(ch='A'; ch<= 'E'; ch++)       switch(ch) {         case 'A':           Console.WriteLine("ch is A");           break;         case 'B':           Console.WriteLine("ch is B");           break;         case 'C':           Console.WriteLine("ch is C");           break;         case 'D':           Console.WriteLine("ch is D");           break;         case 'E':           Console.WriteLine("ch is E");           break;       }   } }

The output from this program is shown here:

 ch is A ch is B ch is C ch is D ch is E

Notice that this example does not include a default statement. Remember, the default is optional. When not needed, it can be left out.

In C#, it is an error for the statement sequence associated with one case to continue on into the next case. This is called the “no fall-through” rule. This is why case sequences end with a break statement. (You can avoid fall-through in other ways, such as by using the goto, discussed later in this chapter, but break is by far the most commonly used approach.) When encountered within the statement sequence of a case, the break statement causes program flow to exit from the entire switch statement and resume at the next statement outside the switch. The default statement must also not “fall through,” and it too usually ends with a break.

The no fall-through rule is one point on which C# differs from C, C++, and Java. In those languages, one case may continue on (that is, fall through) into the next case. There are two reasons that C# instituted the no fall-through rule for cases. First, it allows the compiler to freely rearrange the order of the case statements, perhaps for purposes of optimization. Such a rearrangement would not be possible if one case could flow into the next. Second, requiring each case to explicitly end prevents a programmer from accidentally allowing one case to flow into the next.

Although you cannot allow one case sequence to fall through into another, you can have two or more case statements refer to the same code sequence, as shown in this example:

 // Empty cases can fall through. using System; class EmptyCasesCanFall {   public static void Main() {     int i;     for(i=1; i < 5; i++)       switch(i) {         case 1:         case 2:         case 3: Console.WriteLine("i is 1, 2 or 3");           break;         case 4: Console.WriteLine("i is 4");           break;       }   } }

The output is shown here:

 i is 1, 2 or 3 i is 1, 2 or 3 i is 1, 2 or 3 i is 4

In this example, if i has the value 1, 2, or 3, then the first WriteLine( ) statement executes. If it is 4, then the second WriteLine( ) statement executes. The stacking of cases does not violate the no fall-through rule, because the case statements all use the same statement sequence.

Stacking case statements is a commonly employed technique when several cases share common code. This technique prevents the unnecessary duplication of code sequences.

Nested switch Statements

It is possible to have a switch as part of the statement sequence of an outer switch. This is called a nested switch. The case constants of the inner and outer switch can contain common values and no conflicts will arise. For example, the following code fragment is perfectly acceptable:

 switch(ch1) {   case 'A': Console.WriteLine("This A is part of outer switch.");     switch(ch2) {       case 'A':         Console.WriteLine("This A is part of inner switch");         break;       case 'B': // ...     } // end of inner switch     break;   case 'B': // ...




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net