C# Switch Expression Examples
In modern C#, the switch statement has evolved significantly with the introduction of switch expressions, enhancing code readability and efficiency. This article explores various facets of using switch statements and expressions, providing a deep dive into their syntax and practical applications.
C# Switch Expression Multiple Cases
Switch expressions introduced in C# 8.0 allow for multiple cases to be handled in a single line, simplifying the syntax and improving readability. For example:
var number = 3;
var result = number switch {
1 or 2 => "One or Two",
3 or 4 => "Three or Four",
_ => "Other"
};
C# Switch Statement
The traditional switch statement in C# executes different blocks of code based on the value of a variable. It's structured to handle complex logic by providing a case and break for each potential match:
var day = 4;
switch (day) {
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Another day");
break;
}
C# Switch Expression vs Statement
While switch statements perform actions, switch expressions return values based on a match. Expressions are more concise and can be used directly in an expression context:
var status = 200;
var message = status switch {
200 => "Success",
404 => "Not Found",
_ => "Unknown"
};
C# Switch Expression Fall Through
Unlike switch statements, switch expressions do not support fall through, meaning each case must handle its outcome completely, thus eliminating accidental execution of multiple cases:
// This is not possible in switch expressions and will throw a compile-time error.
C# Switch on Type
Switch expressions can elegantly handle type patterns, allowing actions based on the type of an object without explicit type checks or casting:
object obj = 42;
var typeInfo = obj switch {
int i when i > 0 => "Positive integer",
string s => "String value",
_ => "Unknown type"
};
C# Switch Lambda
Lambdas can be used within switch expressions to execute more complex operations inline. This is particularly useful when each case requires more than a simple return:
var response = 200;
var action = response switch {
200 => () => Console.WriteLine("OK"),
404 => () => Console.WriteLine("Not Found"),
_ => () => Console.WriteLine("Unknown Status")
};
action();
C# Switch Expression
Switch expressions are most beneficial for mapping from a value to a result directly, providing a clear and concise alternative to switch statements:
var color = "red";
var hex = color switch {
"red" => "#FF0000",
"green" => "#00FF00",
"blue" => "#0000FF",
_ => "#FFFFFF"
};
C# Switch Case Multiple Conditions
C# 9.0 and later support using tuples in switch expressions, allowing multiple conditions to be checked in a single case:
var state = "NY";
var city = "NYC";
var location = (state, city) switch {
("NY", "NYC") => "New York City",
("NY", _) => "Other part of New York",
_ => "Outside New York"
};
C# Switch Statement String
Switch statements traditionally handle strings efficiently, allowing for straightforward text-based case checks:
var fruit = "apple";
switch (fruit) {
case "apple":
Console.WriteLine("Apple selected");
break;
case "banana":
Console.WriteLine("Banana selected");
break;
default:
Console.WriteLine("No fruit selected");
break;
}
C# Switch New Syntax
The newer switch syntax further simplifies handling different scenarios using less verbose and more intuitive code, especially with the inclusion of pattern matching in C# 9.0 and later:
var tool = "hammer";
var use = tool switch {
"hammer" => "Build something",
"screwdriver" => "Tighten a screw",
_ => "Unknown tool"
};
Switch expressions and statements in C# provide powerful tools for branching logic based on the value of variables. The evolution of these constructs in C# enhances code clarity and conciseness, making it easier to write and maintain.