CSharp - Stack switch type pattern match by range and by type


The following code use switch to match value by range.

Console.WriteLine in the following code will execute for any floating-point type greater than 1000:

switch (x)
   case float f when f > 1000:
   case double d when d > 1000:
   case decimal m when m > 1000:
         Console.WriteLine ("We can refer to x here but not f or d or m");

In Console.WriteLine statement, you would not know the type of x and which value is assigned.

You can mix and match constants and patterns in the same switch statement.

You can switch on the null value:

case null:
       Console.WriteLine ("Nothing here");

Related Topic