Information Technology Reference
In-Depth Information
More on the switch Statement
A switch statement can have any number of switch sections, including none. The default sec-
tion is not required, as shown in the following example. It is, however, generally considered
good practice to include it, since it can catch potential errors.
For example, the switch statement in the following code has no default case. The switch
statement is inside a for loop, which executes the statement five times, with the value of x start-
ing at 1 and ending at 5 .
for( int x=1; x<6; x++ )
{
switch( x )
{
case 5:
Console.WriteLine("x is {0} -- In Case 5", x);
break;
}
}
The output of this code is the following:
x is 5 -- In Case 5
The following code has only the default case:
for( int x=1; x<4; x++ )
{
switch( x )
{
default:
Console.WriteLine("x is {0} -- In Default case", x);
break;
}
}
This code produces the following output:
x is 1 -- In Default case
x is 2 -- In Default case
x is 3 -- In Default case
Search WWH ::




Custom Search