C# Pattern Matching — Complete Guide
In this tutorial, you'll learn about C# Pattern Matching. We cover key concepts, practical examples, and best practices.
You have a chain of if-else or switch statements that check types, values, or shapes. The logic is hard to read and easy to break. C# pattern matching lets you express these checks as clean, composable patterns.
Wrong
public string Describe(object value)
{
if (value is int)
{
var i = (int)value;
if (i > 0) return "positive";
if (i < 0) return "negative";
return "zero";
}
if (value is string s && s.Length > 0) return $"text: {s}";
return "unknown";
}
Output: Works, but verbose and requires casts.
Right
public string Describe(object value) => value switch
{
int i when i > 0 => "positive",
int i when i < 0 => "negative",
int i => "zero",
string { Length: > 0 } s => $"text: {s}",
null => "null",
_ => "unknown"
};
Output: Same result, but the intent is clear. Each arm is a pattern. The compiler checks exhaustiveness and warns about unreachable arms.
Patterns include type patterns, relational patterns, property patterns, positional patterns, var patterns, discard patterns, and list patterns (C# 11).
Prevention
- Use
switchexpressions instead ofif-elsechains when matching multiple types or shapes. - Use
whenfor additional conditions within a pattern arm. - Use
_(discard) for the default case to ensure exhaustiveness. - Combine with
and,or,notfor complex pattern logic. - Use property patterns to match on nested members without manual extraction.
- Prefer pattern matching over
is+ cast for type checks.
Common Mistakes with pattern matching
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
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
Pattern matching is used extensively in Doda Browser's message routing system. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro