You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
However, there is one disadvantage to this approach compared to a simple if statement. switch requires break in each switch-section. While there were lengthy discussions on this matter, I want to take the risk and suggest to not require break in switch sections in presence of a single block. This way, it feels far more natural and better than if else overall.
This approach works fine. But there are some parts that can be still improved.
While this example could be written via if else statements, we are actually matching against a particular expression i.e. expr.Body but since methods can't be called in patterns, we are needed to use the when clause.
Alternatively, we could relax recursive patterns to also look up for member and extension methods of the static type of the target expression in addition to types (#9005):
I've suggested to use out to inject patterns inside expressions (#11293). Likewise, we can use in to inject expressions inside patterns (suggested by @DavidArno).
Proposal: switch when
Take the following code as a simple example,
To prevent code duplication, one might combine the two
if
's like this:But now the readability has significantly worsened (if you ask me!).
As an alternative, we could use a
switch
construct which does not accept a particular expression to match against,However, there is one disadvantage to this approach compared to a simple
if
statement.switch
requiresbreak
in each switch-section. While there were lengthy discussions on this matter, I want to take the risk and suggest to not requirebreak
in switch sections in presence of a single block. This way, it feels far more natural and better thanif else
overall.This can be also helpful with #11293:
Note:
Member
extension method is defined as follow (#13400).This approach works fine. But there are some parts that can be still improved.
While this example could be written via
if else
statements, we are actually matching against a particular expression i.e.expr.Body
but since methods can't be called in patterns, we are needed to use thewhen
clause.Alternatively, we could relax recursive patterns to also look up for member and extension methods of the static type of the target expression in addition to types (#9005):
The problem is now we can't pass expressions to this method, for example what if we had the following extension method?
I've suggested to use
out
to inject patterns inside expressions (#11293). Likewise, we can usein
to inject expressions inside patterns (suggested by @DavidArno).etc.
The text was updated successfully, but these errors were encountered: