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