Using blocks in C# switch expression?

however I didn't understand where this is addressed in the documentation

This is stated pretty clear here:

There are several syntax improvements here:

  • The variable comes before the switch keyword. The different order makes it visually easy to distinguish the switch expression from the switch statement.
  • The case and : elements are replaced with =>. It's more concise and intuitive.
  • The default case is replaced with a _ discard.
  • The bodies are expressions, not statements.

{ someDir.Delete(); ... MoreActions} is not an expression.

However, you can abuse every feature, as they say :)

You can make the switch expression evaluate to an Action, and invoke that action:

Action a = response switch
{
    "yes" => () => { ... },
     _ => () => { .... }
};
a();

You can even reduce this to a single statement:

(response switch
{
    "yes" => (Action)(() => { ... }),
     _ => () => { ... }
})();

But just don't do this...


As per documentation: The bodies are expressions, not statements.

You can do something like this though:

Action fn = response switch
{
    "yes" => () => { BlockTest(); },
     _ => () => { OldTest(); }
};