Since C# was first introduced, developers have complained about the lack of a range operator in switch constructs. This made switches far less useful in C# than they were in VB. As part of the pattern-matching enhancements for C# 9, this limitation has been addressed.

In this feature, the following patterns will be allowed following the case or is keyword.

  • < constant-expression
  • constant-expression
  • <= constant-expression
  • = constant-expression

This is still more limited than VB in the sense that only constants are allowed. This becomes a problem when you are dealing with dates, times, or other comparable structs, as they do not have a constant representation in C#. (Date/time values can be expressed as a constant in VB, but it is discouraged because one runs into DateTime.Kind issues.) When asked why, Neal Gafter wrote,

It doesn’t do the same thing that pattern-matching was designed to do. Specifically, it was designed to work with constants specifically so that the compiler can analyze, diagnose, and optimize the totality of the set of pattern-matching operations. If the compiler doesn’t know the value it is matching against, it cannot do any of that. That’s not to say it is necessarily a bad idea, but it is a pretty different animal. Do ordinary expressions not satisfy that need?

#c# 9 #.net #development #programming-c #csharp

C# 9: Range Operators in Switch Constructs
2.10 GEEK