A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
A switch
statement is often more concise and understandable than if...else if... else..
statements when testing multiple possible values for a single variable.
Syntax is as follows
switch(expression) {
case constant-expression:
statement(s);
break;
case constant-expression:
statement(s);
break;
// you can have any number of case statements
default : // Optional
statement(s);
break;
}
there are sevaral things that have to consider while using the switch statement
break
statement unless it is an empty statement. In that case execution will continue at the case below it. The break statement can also be omitted when a return
, throw
or goto case
statement is used.Example can be given with the grades wise
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}