Meta Description
Learn how to use the switch statement in C# to simplify complex conditional logic and improve code readability. Discover practical examples of handling multiple conditions with relational patterns, grouped cases, and user menu selections, including how to use the switch expression for modern, compact code.
Introduction
In C# development, if-else statements are often used to control program flow by checking conditions. However, as the number of conditions grows, these structures can become difficult to read and maintain.
For example, consider a performance review system where you need to evaluate an employee’s rating and take specific actions based on the result. Using a switch statement instead of if-else
simplifies such scenarios, making your code cleaner and more maintainable.
Basic Syntax of a Switch Statement
The switch statement evaluates an expression and jumps to a matching case. If no case matches, the default
case runs.
switch (expression)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code for unmatched cases
break;
}
Example 1: Employee Performance Ratings
Let’s evaluate an employee’s performance rating and display a corresponding 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;
}
Why Use Switch Here?
Switch provides a clear structure for handling multiple, mutually exclusive conditions like employee ratings.
Example 2: Evaluating Work Hours with Relational Patterns
Relational patterns in C# allow switch cases to handle ranges of values, making them ideal for scenarios like calculating pay based on work hours.
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;
}
Why Relational Patterns?
Relational patterns simplify checking value ranges, making code more concise and readable compared to if-else
.
Example 3: Grouping Cases for Shared Behavior
When multiple conditions share the same behavior, you can group cases to reduce repetition.
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;
}
Benefits of Grouping Cases:
- Reduces code duplication.
- Groups related conditions logically for better readability.
Example 4: Menu for Account Management
Switch statements are often used in menu-driven programs to handle user input efficiently.
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;
}
Error Handling:
- Use the
default
case to handle invalid inputs gracefully.
Bonus: Switch Expressions
Switch expressions (introduced in C# 8.0) provide a modern alternative to switch statements for simpler scenarios.
int workHours = 35;
string message = workHours switch
{
< 30 => "Part-time employee. No overtime pay.",
>= 30 and < 40 => "Standard hours. Regular pay.",
>= 40 => "Full-time employee. Eligible for overtime pay.",
_ => "Invalid work hours."
};
Console.WriteLine(message);
Why Use Switch Expressions?
- More compact and readable.
- Ideal for scenarios with simple, one-liner outputs.
Practice Assignments
Easy
Write a program that determines the letter grade for a student based on their score:
-
90-100
: A -
80-89
: B -
70-79
: C -
60-69
: D -
< 60
: F
Medium
Implement a switch to classify products based on price ranges:
-
< $20
: Low price. -
$20-$50
: Medium price. -
> $50
: High price.
Difficult
Develop a switch-based role manager for a system:
- Admin: Full access.
- User: Read and write access.
- Guest: Read-only access.
- Unknown role: Display error.
Key Takeaways
- Use switch statements for cleaner, more readable code when handling multiple conditions.
- Leverage relational patterns to evaluate ranges of values.
- Group cases for shared behavior to reduce code duplication.
- Explore switch expressions for modern, compact syntax.
Switch statements are a powerful tool for managing complex conditional logic, improving both readability and maintainability in your C# projects.
Top comments (0)