How does pattern matching in an 'is' expression differ from a traditional type check with 'as' and a null check, and what does it enable?
Short answer
`obj is Type variable` performs the type check AND declares a new, already-cast local variable in ONE expression if the check succeeds — eliminating the separate 'as' cast plus null-check-for-failure pattern, and integrating cleanly with additional pattern conditions (property…
Advertisement
AModel answer
`obj is Type variable` performs the type check AND declares a new, already-cast local variable in ONE expression if the check succeeds — eliminating the separate 'as' cast plus null-check-for-failure pattern, and integrating cleanly with additional pattern conditions (property patterns, relational patterns, etc.) introduced in modern C#.
object value = 42;
// Modern pattern matching:
if (value is int number && number > 0) {
Console.WriteLine($"Positive int: {number}");
}
// Older equivalent, more verbose:
int? asInt = value as int?;
if (asInt.HasValue && asInt.Value > 0) { /* ... */ }Real-world example
Simplifying a type-check-then-use pattern that previously required a separate 'as' cast and null check into one concise expression.
Likely follow-ups
- How do property patterns (like 'obj is Person { Age: > 18 }') extend this same pattern-matching capability further?
Related topics