C# Switch Statements
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →Switch statements in C# provide an efficient way to handle multiple conditions based on a single expression. They offer a cleaner alternative to long chains of if-else statements, especially when dealing with discrete values.
Basic Syntax
The basic structure 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;
default:
// Code to execute if no case matches
break;
}
The expression is evaluated once, and its value is compared against each case. When a match is found, the corresponding code block is executed.
Key Features
- The
breakstatement is required at the end of each case to prevent fall-through. - The
defaultcase is optional but recommended for handling unexpected values. - Multiple cases can be combined if they share the same code block.
Example: Days of the Week
Here's a practical example using a switch statement to handle days of the week:
string day = "Monday";
string message;
switch (day)
{
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
message = "It's a weekday.";
break;
case "Saturday":
case "Sunday":
message = "It's the weekend!";
break;
default:
message = "Invalid day.";
break;
}
Console.WriteLine(message);
This example demonstrates how multiple cases can share the same code block, reducing repetition.
Pattern Matching in Switch Statements
C# 7.0 introduced pattern matching in switch statements, allowing for more complex conditions:
object obj = 42;
switch (obj)
{
case int i when i > 0:
Console.WriteLine("Positive integer");
break;
case int i:
Console.WriteLine("Non-positive integer");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
default:
Console.WriteLine("Unknown type");
break;
}
This advanced feature enables type checking and conditional matching within the switch statement.
Best Practices
- Use switch statements when you have multiple conditions based on a single variable.
- Ensure all possible cases are handled, including a default case.
- Keep case blocks short and focused. Consider extracting complex logic into separate methods.
- Use C# If-Else Statements for more complex conditional logic that doesn't fit well in a switch structure.
Conclusion
Switch statements in C# offer a clean and efficient way to handle multiple conditions. They improve code readability and maintainability, especially when dealing with discrete values. As you continue your C# journey, you'll find switch statements to be a valuable tool in your programming toolkit.
For more control flow structures, explore C# While Loops and C# For Loops.