Ever find yourself mapping multiple string values to the same result? Being a C# developer for a long time, I sometimes forget that the C# has evolved so I still dare to chain case labels or reach for a dictionary. Of course with pattern matching this is no longer necessary. With pattern matching, you can express things inline, declaratively, and with zero repetition.
A small example
I was working on a small script that should invoke different actions depending on the environment. As our developers were using different variations for the same environment e.g. "tst" alongside "test", "prd" alongside "prod". We asked to streamline this a long time ago, but as these things happen, we still see variations in the wild.
This brought me to the following code that is a perfect example for pattern matching:
The or keyword here is a logical pattern combinator, not a boolean operator. It matches if either of the specified patterns is satisfied. The result is a single, tidy case instead of two almost identical cases or a helper method.
The same pattern syntax works for ranges and negations, which is especially powerful with numeric or property patterns:
Key rule: and binds tighter than or, just like && and || in boolean logic. Use parentheses when combining them to make precedence explicit and your intent clear.
Beyond saving lines, these kind of logical patterns make the intent of each arm self-documenting. Combined with the discard pattern _ as a safe default, switch expressions become a concise, exhaustive decision table right in your code.