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.
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.
break
statement is required at the end of each case to prevent fall-through.default
case is optional but recommended for handling unexpected values.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.
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.
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.