Daniel
Daniel

Reputation: 7724

Is is possible to have multiple lines in a switch statement of C# 8?

In C# 8 we have the return switch statement, which looks like this:

return a switch
{
    1 => "op1",
    2 => "op2",
    3 => "op3",
    _ => "default"
};

Is it possible to log something before returning? For example:

return a switch
{
    1 => { Console.WriteLine("op1"); return "op1"; },
    2 => "op2",
    3 => "op3",
    _ => "default"
};

Upvotes: 0

Views: 183

Answers (1)

Joshua
Joshua

Reputation: 43327

Taking a page from javascript:

return a switch
{
    1 => ((Func<string>) (() => { Console.WriteLine("op1"); return "op1";}))(),
    2 => "op2",
    3 => "op3",
    _ => "default"
};

If I have to review this I want to see a really good reason why this is isn't a switch statement though.

I've had to do something like this in an exception filter a few times, where you can't put a statement. It's the kind of thing nobody likes but every once in awhile has to be done.

Upvotes: 5

Related Questions