C# switch statement
Description
switch
statements let you branch program execution
based on a selection of possible
values that a variable may have.
Syntax
It has the following format:
switch(expression) {
case constant1:
statement sequence //ww w. j a v a 2 s .c o m
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
.
.
.
default:
statement sequence
break;
}
The switch expression must be of an integer type, such as char, byte, short, or int, or of type string.
The default statement sequence is executed if no case constant matches the expression. The default is optional. If default is not present, no action takes place if all matches fail. When a match is found, the statements associated with that case are executed until the break is encountered.
Example 1
Example for switch statement
using System; // w ww. ja va2 s .co m
class MainClass {
public static void Main() {
int i;
for(i=0; i<10; i++)
switch(i) {
case 0:
Console.WriteLine("i is zero");
break;
case 1:
Console.WriteLine("i is one");
break;
case 2:
Console.WriteLine("i is two");
break;
case 3:
Console.WriteLine("i is three");
break;
case 4:
Console.WriteLine("i is four");
break;
default:
Console.WriteLine("i is five or more");
break;
}
}
}
The code above generates the following result.
Example 2
The following code displays the detailed message for a grading schema.
using System;/*from w w w.j a va2 s .co m*/
class Program
{
static void Main(string[] args)
{
string ch = "C";
switch (ch)
{
case "A":
Console.WriteLine("Excellent");
break;
case "B":
Console.WriteLine("Good");
break;
case "C":
Console.WriteLine("OK");
break;
case "D":
Console.WriteLine("No so good");
break;
case "E":
Console.WriteLine("Failed");
break;
}
}
}
The output:
You can use the string and enum value as the switch control value.
Example 3
We can group statements together to shorten the code.
using System;//from w ww .ja v a 2s . c om
class Program
{
static void Main(string[] args)
{
string ch = "C";
switch (ch)
{
case "A":
case "B":
case "C":
Console.WriteLine("Pass");
break;
case "D":
case "E":
Console.WriteLine("Failed");
break;
}
}
}
The output:
Empty cases can fall through
using System; /*from www . j a va 2s . c om*/
class MainClass {
public static void Main() {
int i;
for(i=1; i < 5; i++)
switch(i) {
case 1:
case 2:
case 3: Console.WriteLine("i is 1, 2 or 3");
break;
case 4: Console.WriteLine("i is 4");
break;
}
}
}
The code above generates the following result.