Hacker News new | ask | show | jobs
by sbelskie 1048 days ago
FWIW, this a switch expression rather than a switch statement.

But in any case I really love this addition to the language but the inability to have multi-line or block expression arms is a constant annoyance for me.

You can even combine these with the new one line record syntax to create a poor man’s discriminated union.

1 comments

Your pedantic correction is actually important for another reason: the switch expression (unlike the switch statement) is defined at the language level as an expression (evaluating to/“returning” a value), which would be ok except C# doesn’t (at the language level) have a void/unit type, meaning the switch statement has to return an actual value, limiting the places you can use it compared to the F# counterpart (or the match expression from rust, etc) to very specific cases, usually those performing an assignment.

The workaround for that is the same as the workaround for the really lame one line limitation: you need to call a (preferably (static) local) function in the handler portion and then return something like `true` assigned to a discard. Hacks all around!

Eg

_ = foo switch a when … => CaseA(foo), _ => CaseB(foo);

With CaseA and CaseB returning bool in order to call a function depending on the value of foo rather than assign a value.