Information Technology Reference
In-Depth Information
Switch Labels
The expression following the keyword
case
, in a switch label
Must be a constant expression, and therefore must be completely evaluable by the com-
piler at
compile
time
Must be of the same type as the test expression
For example, Figure 9-5 shows three sample
switch
statements.
Figure 9-5.
Switch statements with different types of switch labels
Although C# does not allow falling through from one switch section to another.
You can attach multiple switch labels to any switch section.
Following the statement list associated with a case, there must be a
break
or
goto
state-
ment before the next switch label, unless there are
no intervening executable statements
between the switch labels.
For example, in the following code there are no executable statements between the first
three switch labels, so it is perfectly fine to have one follow the other. In cases 5 and 6, however,
there is an executable statement between them, so there must be a
break
or
goto
statement.
switch( x )
{
case 1: // Acceptable
case 2:
case 3:
... // Execute this code if x equals 1, 2 or 3
break;
case 5:
y = x + 1;
case 6: // Not acceptable because there is no break
...