The switch statement ( Select Case in VB ) executes embedded statements within a case block whose label matches the value of the switch expression.
The switch statement takes the form:
switch ( expression ) {
case label :
... statements ...
jump-statement;
default:
... statements ...
jump-statement;
}
Select Case expression
Case label
... statements ...
Case Else
... statements ...
End Select
switch ( expression ) {
case label :
... statements ...
jump-statement;
default:
... statements ...
jump-statement;
} |
|
C# |
VB |
JScript |
- The switch statement can include any number of case statements, but no two case statements within the same switch block can have the same value.
- The optional default label ( Case Else in VB ) provides a statement to execute if none of the case values matches expression.
- The given value for each case label must denote a value of a type that is implicitly convertible to the governing type of the switch expression.
NOTE: In C# and JScript, if more than one statement follows a control statement, such as a case statement, the statements must be enclosed within braces { }.
A switch ( or select ) statement is executed as follows:
- The switch ( or select ) expression is evaluated and converted to the governing type.
- If one of the values specified in a case label is equal to the value of the switch expression, the statements following the matched case label is executed.
- If none of the values specified in case labels is equal to the value of the switch expression, and if a default label is present ( Case Else in VB ), the statements following the default label are executed.
- If none of the values specified in case labels is equal to the switch expression, and if no default label is present, control is transferred to the statement after the switch block ( End Select in VB ).
In C# and JScript, if a case label matches expression, the statements within that case block are executed up to the jump-statement, which can either be a break, goto case, or goto default statement. When the jump-statement is break, processing ends in the block where it appears, and control is transferred to the statement after the switch block; otherwise, control is transferred to the statement specified in the jump-statement. The jump-statement is required in each case block, as execution of a case block is not permitted to "fall through" to the next case block.
The following example demonstrates use of a switch statement to display a randomly selected ad depending on which item was chosen in a listbox.
Show me
Below are links to further code examples that illustrate using the switch statement in ASP.NET web forms.