C# 8.0 enhancements with pattern matching

C# 8.0 language features include pattern matching similar to that within F#.

Tuples have become a first class citizen of C# 8.0, so we can write something like this

public (string, int) CreateTuple(string s)
{
   return (s, s.Length);
}

This results in a ValueType being created, which can still be accessed using properties Item1 and Item2, however we can also use tuples within pattern matching, for example

var t = CreateTuple("Ten");
switch (t)
{
   case (string s, 1):
      return $"Single Character {s}";
   case (string s, int l):
      return $"{s}:{l}");
}      

In the above we’re matching firstly against a tuple where the first argument is a string and the second an int with value 1, the second case statements is basically going to catch everything else. Obviously the “catch all” must go after the more specific pattern match.

This can be tidied further by using expressions. So the above becomes

return t switch
{
   (string s, 1) => $"Single Character {s}",
   (string s, int l) => $"{s}:{l}"
};