A switch statement allows a variable to be tested for equality against a list of values. It is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
.
.
.
case valueN: // statement sequence
break;
default: // default statement sequence
}
The switch statement can be used to replace the if...else if
statement in C#.
if...else if
statement is that the codes will look much cleaner and readable with switch.Let's consider the following simple example of a switch statement.
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
Let's run the above code and it will print the following output on the console window.
Case 1
int
, char
, byte
, short
, enum
, or string
type.break
statement.The multiple labels are appropriate when you want to execute the same structure in more than one case. Let's consider the following example.
int number = 6;
switch (number)
{
case 1:
case 4:
case 6:
case 8:
case 10:
Console.WriteLine("The number is not prime!");
break;
case 2:
case 3:
case 5:
case 7:
Console.WriteLine("The number is prime!");
break;
default:
Console.WriteLine("Unknown number!");
break;
}
In the above example, the multiple labels are implemented using case statements without a break statement.
The above example displays the following output.
The number is not prime!