How to Use Switch Expression in C# - Simple Guide
In C#, use the
switch expression to evaluate a value and return a result based on matching patterns in a concise way. It uses the syntax value switch { pattern => result, ... } to replace longer switch statements with cleaner code.Syntax
The switch expression evaluates a value and matches it against patterns to return a result. It uses the form:
value: the variable or expression to check.switch: keyword to start the expression.{ pattern => result, ... }: a set of patterns and corresponding results separated by commas._: a discard pattern that matches anything (like default).
csharp
var result = value switch { pattern1 => result1, pattern2 => result2, _ => defaultResult };
Example
This example shows how to use a switch expression to convert a day number to its name.
csharp
using System; class Program { static void Main() { int day = 3; string dayName = day switch { 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", 4 => "Thursday", 5 => "Friday", 6 => "Saturday", 7 => "Sunday", _ => "Invalid day" }; Console.WriteLine(dayName); } }
Output
Wednesday
Common Pitfalls
Common mistakes when using switch expressions include:
- Not covering all possible input values, which causes a
SwitchExpressionExceptionat runtime. - Using statements instead of expressions; switch expressions must return a value directly.
- Forgetting the discard pattern
_to handle unexpected cases.
Always ensure every input is matched or use _ as a fallback.
csharp
/* Wrong: Missing fallback pattern causes runtime error */ var result = 10 switch { 1 => "One", 2 => "Two" // Missing _ => ... }; /* Right: Add fallback pattern */ var safeResult = 10 switch { 1 => "One", 2 => "Two", _ => "Other" };
Quick Reference
Tips for using switch expressions:
- Use
switchexpressions for concise value-based branching. - Always include a fallback pattern
_to avoid exceptions. - Patterns can be constants, types, or conditions (with
whenclauses). - Switch expressions return a value and cannot contain statements.
Key Takeaways
Switch expressions provide a concise way to return values based on matching patterns.
Always include a fallback pattern (_) to handle unexpected inputs safely.
Switch expressions return values directly and cannot contain statements.
Patterns can be constants, types, or conditional with when clauses.
Use switch expressions to write cleaner and more readable branching code.