Modern C# pattern matching unifies type tests, property deconstruction, and switch expressions—more expressive than chained if/else or instanceof checks in Java.
is patterns and switch
if (obj is string { Length: > 0 } s) {
Console.WriteLine(s);
}
string label = shape switch {
Circle c => $"circle r={c.Radius}",
Rectangle r => $"rect {r.Width}x{r.Height}",
_ => "unknown"
};
Relational and logical patterns
int score = 85;
string grade = score switch {
>= 90 => "A",
>= 80 => "B",
_ => "C"
};
Important interview questions and answers
- Q: Switch expression vs statement?
A: Expressions return values and use=>arms; statements usecase/breakfor side effects. - Q: Exhaustiveness?
A: Compiler warns when switch on enums/types misses cases—use_discard for defaults.
Self-check
- What does the _ arm represent?
- How do property patterns help with null checks?
Tip: Combine is patterns with switch expressions—cleaner than long if/else chains for type and shape checks.
Interview prep
- is pattern vs cast?
ispatterns test and bind in one step—safer than manual cast followed by null check.- switch expression exhaustiveness?
Compiler warns when not all cases are covered—especially useful with enums and records.