What is pattern matching in C#?
Answer
Pattern matching in C# enables concise conditional logic based on the shape or value of data. Evolved significantly from C# 7 to C# 11+. Type pattern: if (obj is string s) { Console.WriteLine(s.Length); }. Switch expression (C# 8+): string desc = shape switch { Circle c => $"Circle r={c.Radius}", Rectangle r => $"Rect {r.Width}x{r.Height}", _ => "Unknown" };. Property pattern: if (person is { Age: >= 18, Name: "Alice" }) { }. Tuple pattern: (a, b) switch { (0, _) => "a is zero", (_, 0) => "b is zero", _ => "neither" };. List pattern (C# 11+): if (arr is [1, 2, ..]) { }. Relational patterns: score switch { >= 90 => "A", >= 80 => "B", _ => "F" }. Pattern matching replaces complex if/else chains and switch statements with more readable, exhaustive checks.
Previous
What is a record type in C#?
Next
What is the difference between ref, out, and in parameters in C#?