C# Tutorial - Dissecting Our Seventh Application - The switch (case-break) Statement


The conditional statement switch, selects one of a number of possible statements for execution based on a value of an expression. The switch statement takes the following form:

switch( expression )
{
  case constant-expression:
    statement
    jump-statement
  [default:
    statement
    jump-statement]
}

Where:

  • expression - An integral or string type expression.

  • statement - The embedded statement(s) to be executed if control is transferred to the case or the default.

  • jump-statement - A jump statement that transfers control out of the case body.

  • constant-expression - Control is transferred to a specific case according to the value of this expression.

Control is transferred to the case statement whose constant-expression matches expression. The switch statement can include any number of case instances, but no two case constants within the same switch statement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the jump-statement transfers control out of the case body.

The governing type of a switch statement is established by the switch expression. If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the switch statement.

All switch statements should include a default statement to catch any unwanted inputs.

Jump Statements

Notice that the jump-statement is required after each block, including the last block whether it is a case statement or a default statement. If expression does not match any constant-expression, control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch. The main two types of jump-statement used are break and goto.

The break statement terminates the closest enclosing loop or conditional statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.

Unlike C and C++, jump-statements are mandatory. Program flow is not allowed to fall through to the next case statement, hence the use of the goto statement. The goto statement transfers the program control directly to a labelled statement and takes the following form:

goto case constant-expression;

<< Previous Contents Next >>

© Publicjoe, 2008