C# Tutorials
C# Methods
C# Classes
C# Examples
Use the switch statement to select one of the many code blocks to be used.
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
This is how it works:
The example below uses the number of days of the week to calculate the name of the day of the week:
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
// Outputs "Thursday" (day 4)
When C# reaches the break keyword, it exits the switch block.
This will stop additional code creation and case testing within the block.
Once the game is over, and the job is over, it’s break time. No further testing is required.
The default keyword is optional and specifies a specific code to apply in case of no match:
int day = 4;
switch (day)
{
case 6:
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
Console.WriteLine("Looking forward to the Weekend.");
break;
}
// Outputs "Looking forward to the Weekend."