Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Allows an integral expression (constant, variable, enum, or a class type with a single converstion conversion function to an integral or enumerated value) to be tested against a number of other constant or literal integral expressions.

It’s form is as follows -

Example

Result

Code Block
    static  void    Main( string[] args )
    {
        int index = 2;

        if( index == 1 )
            Console.WriteLine("Index has a value of 1");
        else if( index == 2 || index == 3 )
            Console.WriteLine("Index could be 2 or 3");
        else if ( index == 4 )
            Console.WriteLine("Index has a value of 4");
        else
            Console.WriteLine("Index was NOT 1, 2, or 3");
    }

In this example the message “Index could be 2 or 3” is printed.

Notice the use the variable “index” in multiple places. It’s very easy for these statements to become unwieldly.

Code Block
        int index = 2;

        switch( index )
        {
            case 1: Console.WriteLine("Index has a value of 1");
                break;
            case 2:
            case 3: Console.WriteLine("Index could be 2 or 3");
                break;
            case 4: Console.WriteLine("Index has the value of 4");
                break;
            default: Console.WriteLine("Index was NOT 1, 2, or 3");
                break;
        }

In this example the message “Index could be 2 or 3” is printed.

Switch statements are fairly efficient tests for if conditions. The compiler is smart enough to generate code so that each case statement is not tested.

When a break statement is hit (lines 6, 9, 11, and 13), program execution jumps to the end of the code block (line 34).

The break statement is taken directly from the C/C++ language and is mandatory in the default statement but not in the other statements as shown in the code sample.

The order of the case statements is flexible, but default must be the last statement if used.

Info

FAQ: Why can't I use other comparisons other than the implicit == within each branch of a switch statement? The switch statement is only suitable for discreet == comparisons -- if you want more flexibility, you must choose to use full if ... else if ... else notation.

FAQ: Does it matter what order I specify the branches in? No! (except default must come last).