Pattern matching in C# 7.0
April 11, 2018 2 Comments
C# 7.0 introduces a new language feature called pattern matching. If you are familiar with F# then you’ll know what pattern matching is about. Pattern matching is used extensively in F# but has not been available in C# before 7.0. Also, pattern matching is not just a simple feature in F#, but more like a wide range of features. However, C# 7.0 has not yet caught up with all that. C# 7.0 only introduces a small set of features behind pattern matching and can be regarded as syntactic sugar, but it’s a good start. I’d expect that the same F# features will eventually be transferred into C# as well in upcoming updates.
Pattern matching is most often used in “if” or “switch” branches to see if an incoming value matches a certain pattern. If it does then we take that path, otherwise we take another.
Let’s start with a starting point with a base class and two derived classes: