Friday, February 1, 2013

C# Basics: Switch Statement

The switch statement is a form of selection statement that executes some logic based on the value of a given parameter. Its purpose is to replace multiple conditional statements with a single switch statement.

Basic Syntax
switch (expression)
{
       case constant1:
             statement1;
             break;
       case constant2:
             statement2;
             break;
       case constant3:
             statement3;
             break;
       default:
             default statement;
             break;
 }
If the expression’s value does not match any of the constant values in the switch statement, the control flow is transferred to the statement following the default keyword.

The switch statement above can also be written with multiple if statements as follows:

if (expression1)
{
     statement1;
}
else if (expression2)
{
      statement2;
}
else if (expression3)
{
     statement3;
}
else
{
     default statement;
}

Case fall-through
all case statements within a switch statement must have a reachable endpoint. This is typically the break statement. However, any statement that will jump the execution out of the switch statement will also work. These are statements like return and throw. The only exception to this reachable endpoint rule is when there are no statements between case statements.

In the following example, statement 1 is executed if expression is equal to constant1 or constant2.

switch (expression)
{
     case constant1:                    
     case constant2:
            statement1;
            break;
     case constant3:
            statement3;
            break;  
     default:
            default statement;
            break;
}

No comments:

Post a Comment