C# Switch Expression — Complete Guide
In this tutorial, you'll learn about C# Switch Expression. We cover key concepts, practical examples, and best practices.
You write a traditional switch statement with case, break, and default. It takes fifteen lines to express a simple mapping. The switch expression reduces that to a single expression with clean arrow syntax.
Wrong
public string GetStatusText(int statusCode)
{
switch (statusCode)
{
case 200: return "OK";
case 201: return "Created";
case 400: return "Bad Request";
case 404: return "Not Found";
case 500: return "Server Error";
default: return "Unknown";
}
}
Output: Works but verbose. Easy to forget break or return.
Right
public string GetStatusText(int statusCode) => statusCode switch
{
200 => "OK",
201 => "Created",
400 => "Bad Request",
404 => "Not Found",
500 => "Server Error",
_ => "Unknown"
};
Output: Same result. The switch expression returns a value. Each arm is pattern => result. The _ discard handles the default case.
Switch expressions support all pattern types: type patterns, relational patterns, property patterns, and more.
Prevention
- Use switch expressions for simple value-to-value mappings (enums, status codes, option types).
- Use
_(discard) as the default arm — the expression must be exhaustive. - Combine with
whenclauses for conditional arms. - Use
switchstatements instead of expressions when you need side effects per arm. - Use
{ }for property patterns when matching shapes:{ Name: "admin" } => "Admin". - Keep arms simple — if an arm body is complex, extract it into a method.
Common Mistakes with switch expression
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Switch expressions power the command dispatch system in Doda Browser's extension framework. For more, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro