Meta Description:
Learn how to use the switch statement in C# to simplify complex conditional logic and improve code readability. Discover how to handle multiple conditions, use relational patterns, and group cases together for shared behavior. This guide includes practical examples, from evaluating employee performance to handling user menu selections.
In C# development, you'll likely use many if-else statements. They help us control the flow of execution by checking conditions, but sometimes, as the number of conditions grows, it becomes hard to manage and read. In such cases, using a switch statement can make the code more readable and maintainable.
Why Use switch
Instead of if-else
?
When you have many conditions to check, using if-else if-else
combinations can become cumbersome. Consider a scenario where you need to evaluate multiple values for a variable and execute different code for each. While this works with if-else
, the code can quickly become difficult to read and maintain.
The switch statement offers a cleaner way to handle such scenarios. Instead of repeatedly checking conditions with if-else
, you can use switch
to evaluate an expression and jump directly to a matching case.
Syntax of a switch
Statement
The switch keyword is followed by an expression inside parentheses. This expression is evaluated, and based on the result, the execution jumps to one of the case statements. Each case
compares the switch expression to a constant or pattern. Once a match is found, the corresponding code runs until a break statement is encountered.
Here is a simple structure of a switch
statement:
switch (expression)
{
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if no cases match
break;
}
Example: Switch for Employee Performance Ratings
Let’s say we are building a performance review system. Based on an employee's rating, we want to display a different message.
int rating = 4;
switch (rating)
{
case 5:
Console.WriteLine("Outstanding performance!");
break;
case 4:
Console.WriteLine("Excellent performance!");
break;
case 3:
Console.WriteLine("Good performance.");
break;
case 2:
Console.WriteLine("Needs improvement.");
break;
case 1:
Console.WriteLine("Unsatisfactory performance.");
break;
default:
Console.WriteLine("Invalid rating.");
break;
}
Explanation:
- If the employee's rating is
5
, the program prints "Outstanding performance!". - For a rating of
4
, it prints "Excellent performance!" and so on. - The
default
case catches any invalid ratings that don't match 1 through 5.
Using Relational Expressions in a Switch Statement
In C#, switch expressions can also use relational patterns like less than
or greater than
to evaluate conditions, making the switch even more flexible.
Example: Evaluating Work Hours
Let’s check an employee’s work hours to determine whether they qualify for overtime pay, bonus pay, or standard pay.
int workHours = 45;
switch (workHours)
{
case < 30:
Console.WriteLine("Part-time employee. No overtime pay.");
break;
case >= 30 and < 40:
Console.WriteLine("Standard hours. Regular pay.");
break;
case >= 40:
Console.WriteLine("Full-time employee. Eligible for overtime pay.");
break;
default:
Console.WriteLine("Invalid work hours.");
break;
}
Explanation:
- For
workHours
less than 30, we treat the employee as part-time. - If they work between 30 and 40 hours, they get standard pay.
- For more than 40 hours, they qualify for overtime pay.
Grouping Cases in Switch
You may encounter scenarios where you want to handle multiple cases in the same way. In that case, you can group them by placing multiple case
labels before the same code block.
Example: Shared Behavior for Low Work Hours
If employees work either less than 20 hours or more than 50 hours, we want to give them a different message.
int workHours = 55;
switch (workHours)
{
case < 20:
case > 50:
Console.WriteLine("Special work hours. Review schedule.");
break;
case >= 20 and <= 50:
Console.WriteLine("Standard work hours.");
break;
default:
Console.WriteLine("Invalid input.");
break;
}
Explanation:
- Both
case < 20
andcase > 50
share the same code block, meaning employees working less than 20 or more than 50 hours get the message "Special work hours."
Switch for Menu Selections
Switch statements are also great for handling menu selections in a user interface. Here’s an example where a user selects different operations to perform.
Example: Menu for Account Management
Console.WriteLine("Select an action: ");
Console.WriteLine("1. Create Account");
Console.WriteLine("2. Update Account");
Console.WriteLine("3. Delete Account");
string selectedAction = Console.ReadLine();
switch (selectedAction)
{
case "1":
Console.WriteLine("Creating a new account...");
break;
case "2":
Console.WriteLine("Updating an existing account...");
break;
case "3":
Console.WriteLine("Deleting an account...");
break;
default:
Console.WriteLine("Invalid selection.");
break;
}
Explanation:
- If the user selects option
1
, we begin the process of creating a new account. - For option
2
, the program initiates the account update. - If the user selects
3
, we start deleting the account. - Any other input triggers the
default
message: "Invalid selection."
Conclusion
The switch statement is a powerful tool for managing multiple conditions in a clean, readable way. It helps you avoid lengthy chains of if-else
conditions and provides an easy-to-read structure for handling different values or patterns. While if-else is perfect for simple conditions, when your code involves multiple options, switch is often a better, more maintainable choice.
Key takeaways:
- Use switch for cleaner, more readable code when evaluating multiple conditions.
- Take advantage of relational patterns in C# to handle ranges of values.
- Group cases together when they share the same behavior.
- Switch is great for menu-driven applications, like selecting actions based on user input.
Top comments (0)