Curriculum
The switch statement is a control flow statement in C# that allows you to execute different code blocks based on the value of a single variable. It provides a more concise way to write code than a series of if-else statements when testing for multiple values of the same variable. The basic syntax of a switch statement in C# is as follows:
switch (expression)
{
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// more cases as needed
default:
// code to execute if none of the cases match
break;
}
Here, expression is the variable or expression whose value you want to test. Each case label specifies a value to compare expression against. If expression matches one of the case labels, the code block following that case label is executed. If none of the case labels match expression, the code block following the default label is executed.
Note that each code block inside a case label must end with a break statement. This tells the compiler to exit the switch statement and continue executing the code after the switch block. If you omit the break statement, the compiler will continue executing the code in the next case block, even if its value does not match expression.
Here is an example of using a switch statement in C#:
int dayOfWeek = 3;
switch (dayOfWeek)
{
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;
default:
Console.WriteLine("Invalid day");
break;
}
In this example, the switch statement tests the value of the variable dayOfWeek and prints the corresponding day of the week to the console. Because dayOfWeek is equal to 3, the code block following the case 3: label is executed, printing “Wednesday” to the console.
You can also use string values in a switch statement. Here is an example:
string color = "red";
switch (color)
{
case "red":
Console.WriteLine("The color is red");
break;
case "green":
Console.WriteLine("The color is green");
break;
case "blue":
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("Unknown color");
break;
}
In this example, the switch statement tests the value of the variable color and prints a message based on its value. Because color is equal to “red”, the code block following the case "red": label is executed, printing “The color is red” to the console.
The switch statement can be a powerful tool in C# that allows you to write code that tests the value of a single variable against multiple possible values. However, it is important to use break statements properly to avoid unexpected behavior in your code.