Understanding Pattern Matching in C# Switch Expressions
Hey .NET community,
I recently ran into an interesting behavior with switch expressions in C#. When using relational patterns, I noticed that including a catch-all pattern (_
) at the end of the switch expression can sometimes cause the compiler to throw an "unreachable code" error. Here’s a comparison of two approaches for a method that provides temperature messages based on the input value:
Original Approach:
Improved Approach:
In the improved approach, the _
pattern is used as a catch-all, but it can lead to a compiler warning if all possible values are already covered by the relational patterns. The compiler can infer that the specified ranges cover all possible values for temperature
, making _
redundant.
Has anyone else encountered this behavior or have insights into why the compiler treats these cases differently?
Looking forward to hearing your thoughts!