In the last three years, we’ve had three different major version releases for C#, each presenting a variety of interesting new features. One of these features was pattern matching, which was introduced on C# 7 and expanded on C# 8 and C# 9. In this series of two articles, I’ll be presenting how this feature can be used to improve your code’s flow control.
In order to allow better readability for flow control checks in the code, pattern matching was introduced, enhancing the operator and the switch command.
The operator now supports pattern matching in three different ways
1. To test if an expression can be cast to a certain type, and if so, casting it to a variable of said type
2. To test if an expression equals a specific constant
3. And finally, to assign an expression to a temporary local variable
In this example, the first condition described in the if statement isn’t really a condition, but a set up of an alias for the expression dollarValue * price, that may now be referred to as simply realValue. The other conditions, then, use it to make their tests without having to repeat the expression.
In addition, the switch command was enhanced, so it can test more than just numbers, enums, or constants.
This example showcases how a switch can now be used to test the type of the variable, add a condition on top of a test and test the null case.
In addition to the improvements made on C# 7 to the switch statement, now the code can be further reduced. When the switch statement is meant to be just a means to choose a return value, it can be written as:
Both the case and break keywords are ommited, and the default clause is replaced with the discard operator. In place of case, now a pattern is used, followed by “=>” and the return value.
In this article, we saw some ways C# implemented pattern matching, starting on the 7th release, and a sneak peak of the 8th version. We still have more to see, both on the 8th and the 9th releases, but I hope this has already been useful.
Until next time!