Search code examples
c#c#-8.0switch-expression

Using blocks in C# switch expression?


I fail to find documentation addressing this issue. (perhaps I am just bad at using google...) My guess is that the answer is negative, however I didn't understand where this is addressed in the documentation. To be precise my question is the following.

Suppose, I want to execute something like this:

DirectoryInfo someDir = new DirectoryInfo(@".\someDir");
Console.WriteLine($"Would you like to delete the directory {someDir.FullName}?");
string response = Console.ReadLine().ToLower();

response switch
{
    "yes" => { someDir.Delete(); ... MoreActions},
     _ => DoNothing()
};

I understand that I can achieve the desired behavior by using the regular switch or if/else, however I was curious whether it is possible to use switch expression in this case.


Solution

  • 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...