How to Use a Switch Statement in C#
A switch statement is a programming construct used to select one block of code from many alternatives based on a single expression. In C#, a switch statement is used to test the value of a given expression against a series of predefined cases. This statement is often used when the programmer needs to test the value of an expression against multiple cases.
In this article, we will learn how to use a switch statement in C# to simplify complex programming logic.
Syntax of a Switch Statement in C#
The syntax of a switch statement in C# is as follows:
“`csharp
switch(expression)
{
case value1:
//code to be executed if the value of expression is equal to value1
break;
case value2:
//code to be executed if the value of expression is equal to value2
break;
default:
//code to be executed if the value of expression doesn’t match any of the cases
break;
}
“`
Here, the expression is evaluated and compared to the list of cases. If the expression matches any of the cases, the corresponding block of code is executed. The break keyword is used to exit the switch statement, and the default keyword is used to handle the case where the expression doesn’t match any of the cases.
Example of Using a Switch Statement in C#
Consider the following example:
“`csharp
int number = 5;
switch (number)
{
case 1:
Console.WriteLine(“Monday”);
break;
case 2:
Console.WriteLine(“Tuesday”);
break;
case 3:
Console.WriteLine(“Wednesday”);
break;
case 4:
Console.WriteLine(“Thrusday”);
break;
case 5:
Console.WriteLine(“Friday”);
break;
default:
Console.WriteLine(“Invalid day”);
break;
}
“`
In this example, we create a variable named number and assign it the value of 5. We then use a switch statement to evaluate the value of the number variable against a series of cases that correspond to the days of the week. In this case, the switch statement matches the value of number to the case for Friday and executes the corresponding block of code.
Conclusion
In conclusion, a switch statement simplifies complex programming logic by allowing you to evaluate the value of an expression against multiple cases. By using a switch statement in C#, you can improve the efficiency of your code and create more readable programs. It is important to remember to use the break keyword to exit the switch statement and the default keyword to handle cases where the expression doesn’t match any of the cases.