While preparing yesterday’s post, I was wondering if I could rewrite the following switch statement to use the new .NET 8 switch expression syntax. Here is the original code: And here is my attempt to rewrite this to a switch expression: Unfortunately this didn’t work and resulted in a compiler error: Only assignment, call, increment, decrement, await and new object expressions can be used as a statement. Turns out that switch expression cannot return void . It must return a value and this value must be consumed and cannot be discarded. Too bad! Maybe this is something that will change in future .NET versions as hinted here : The switch_expression is not permitted as an expression_statement. We are looking at relaxing this in a future revision. More information Recursive pattern matching - C# feature specifications | Microsoft Learn switch expression - Evaluate a pattern match expression using the `switch` expression - C# | Microsoft Learn
Although C# remains an object-oriented programming language, it has incorporated more and more functional techniques over the years. One of this techniques is ‘pattern matching’. On the Microsoft Learn website , it is explained like this: Pattern matching is a technique where you test an expression to determine if it has certain characteristics. Not so sexy right? In fact it is rather boring described like this. That is because pattern matching is not something fancy new. It is here to simplify complex if-else statements into more compact and readable code. Pattern matching does not aim at writing code that cannot be written without. Its only purpose is to have more concise and elegant code. There are multiple supported pattern types; constant patterns , declaration patterns , relational patterns , and so on… In this post I want to talk about a specific pattern; the type pattern. The type pattern in itself is quite simple, it checks the runtime type of an express