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:
public static void Handle(ICommand command){ | |
switch(command){ | |
case CreateUserCommand createCommand: CreateUser(createCommand.Name,createCommand.Email); break; | |
case DeleteUserCommand deleteCommand: DeleteUser(deleteCommand.UserId);break; | |
default: throw new InvalidOperationException("Unknown command type"); | |
} | |
} |
And here is my attempt to rewrite this to a switch expression:
public static void Handle(ICommand command) => command switch { | |
CreateUserCommand createCommand=> CreateUser(createCommand.Name,createCommand.Email); break, | |
DeleteUserCommand deleteCommand => DeleteUser(deleteCommand.UserId), | |
_ => throw new InvalidOperationException("Unknown command type") | |
}; | |
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