Previous Page
Next Page

Using switch Statements

Sometimes when you write a cascading if statement, all the if statements look very similar, because they all evaluate an identical expression. The only difference is that each if compares the result of the expression with a different value. For example:

if (day == 0) 
    dayName = "Sunday"; 
else if (day == 1) 
    dayName = "Monday"; 
else if (day == 2) 
    dayName = "Tuesday"; 
else if (day == 3) 
    ... 
else 
    dayName = "Unknown";

In these situations, you can often rewrite the cascading if statement as a switch statement to make your program more efficient and more readable.

Understanding switch Statement Syntax

The syntax of a switch statement is as follows (switch, case, and default are keywords):

switch ( controllingExpression ) 
{ 
case constantExpression : 
    statements 
    break; 
case constantExpression : 
    statements 
    break; 
... 
default : 
    statements 
    break; 
}

The controllingExpression is evaluated once, and the statements below the case whose constantExpression value is equal to the result of the controllingExpression run as far as the break statement. The switch statement then finishes, and the program continues at the first statement after the closing brace of the switch statement.

If none of the constantExpression values are equal to the value of the controllingExpression, the statements below the optional default label run.

NOTE
If the value of the controllingExpression does not match any of the case labels and there's no default label, program execution continues with the first statement after the closing brace of the switch statement.

For example, you can rewrite the previous cascading if statement as the following switch statement:

switch (day) 
{ 
case 0 : 
    dayName = "Sunday"; 
    break; 
case 1 : 
    dayName = "Monday"; 
    break; 
case 2 : 
    dayName = "Tuesday"; 
    break; 
... 
default : 
    dayName = "Unknown"; 
    break; 
}
Following the switch Statement Rules

The switch statement is very useful, but, unfortunately, you can't always use it when you might like to. Any switch statement you write must adhere to the following rules:

NOTE
The break statement is the most common way to stop fall-through, but you can also use a return statement or a throw statement. The throw statement is described in Chapter 6, “Managing Errors and Exceptions.”

In the following exercise, you will complete a program that reads the characters of a string and maps each character to its XML representation. For example, the '<' character has a special meaning in XML (it's used to form elements) and must be translated into "&lt;". You will write a switch statement that tests the value of the character and traps the special XML characters as case labels.

Write switch statements
  1. Start Visual Studio 2005.

  2. Open the SwitchStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 4\SwitchStatement folder in your My Documents folder.

  3. On the Debug menu, click Start Without Debugging.

    Visual Studio 2005 builds and runs the application. There are two text boxes separated by a Copy button.

    Graphic
  4. Type the following sample text into the upper text box:

    inRange = (lo <= number) && (number <= hi);
  5. Click Copy.

    The statement is copied verbatim into the lower text box, and no translation of the '<' character occurs.

  6. Close the form.

  7. Display the code for Form1.cs in the Code and Text Editor window. Locate the copyOne method.

    The copyOne method copies one character from the upper text box to the lower text box. At the moment, copyOne contains a switch statement with a single default section.

    In the following few steps, you will modify this switch statement to convert characters that are significant in XML to their XML mapping. For example, the '<' character will be converted to the string "&lt;".

  8. Add the following statements to the switch statement, above the default label:

    case '<' : 
        target.Text += "&lt;"; 
        break; 
    case '>' : 
        target.Text += "&gt;"; 
        break; 
    case '&' : 
        target.Text += "&amp;"; 
        break; 
    case '\"' : 
        target.Text +=  "&#34;"; 
        break; 
    case '\'' :   
        target.Text += "&#39;"; 
        break;
    NOTE
    The back-slash (\) in the final two cases is an escape character that causes the following characters (" and ') to be treated literally, rather than as characters delimiting a string or character constant.
  9. On the Debug menu, click Start Without Debugging.

    Visual Studio 2005 builds and runs the application.

  10. Type the following statement into the upper text box:

    inRange = (lo <= number) && (number <= hi);
  11. Click Copy.

    The statement is copied into the lower text box. This time, each character undergoes the XML mapping implemented in the switch statement.

  12. Close the form.


Previous Page
Next Page