| The switch statement is similar to the statement from C, C++ and Java.
Unlike C, each case statement must finish with a jump statement (which can be break or goto or return). In other words, C# does not support "fall through" from one case statement to the next (thereby eliminating a common source of unexpected behaviour in C programs). However "stacking" of cases is allowed, as in the example below. If goto is used, it may refer to a case label or the default case (e.g. goto case 0 or goto default).
The default label is optional. If no default case is defined, then the default behaviour is to do nothing.
A simple example:
switch (nCPU)
{
case 0:
Console.WriteLine("You don't have a CPU! :-)");
break;
case 1:
Console.WriteLine("Single processor computer");
break;
case 2:
Console.WriteLine("Dual processor computer");
break;
// Stacked cases
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
Console.WriteLine("A multi processor computer");
break;
default:
Console.WriteLine("A seriously parallel computer");
break;
}
A nice improvement over the C switch statement is that the switch variable can be a string. For example:
switch (aircraft_ident)
{
case "C-FESO":
Console.WriteLine("Rans S6S Coyote");
break;
case "C-GJIS":
Console.WriteLine("Rans S12XL Airaile");
break;
default:
Console.WriteLine("Unknown aircraft");
break;
}
All text is available under the terms of the GNU Free Documentation License
Source : Wikibooks |