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
1 2 3 4 | 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
1 2 3 4 5 6 7 8 | 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
1 2 3 4 5 | return t switch { ( string s, 1) => $ "Single Character {s}" , ( string s, int l) => $ "{s}:{l}" }; |