Roslyn: Pattern match variable scope

Created on 18 Nov 2016  Â·  2Comments  Â·  Source: dotnet/roslyn

In the Roslyn Pattern Matching spec it states that:

The scope of a pattern variable is as follows:

If the pattern appears in the condition of an if statement, its scope
is the condition and controlled statement of the if statement, but not
its else clause.

However the latest Microsoft "What's new" posts and presentations are showing this example:

public void PrintStars(object o)
{
    if (o is null) return;     // constant pattern "null"
    if (!(o is int i)) return; // type pattern "int i"
    WriteLine(new string('*', i));
}

As you can see, the pattern variables – the variables introduced by a pattern – are similar to the out variables described earlier, in that they can be declared in the middle of an expression, and can be used within the nearest surrounding scope.

When / why has the scoping for if statements changed from the spec?

I feel that this scoping is fairly unintuitive and contradictory to all the other 'block' constructs like catch and using.

Most helpful comment

@DavidArno - Thanks for the information and source!

I think this is a bad choice for the language, and I find it a shame that there is an assumptive justification around 'new keywords' being somehow worse than unintuitive and contradictory semantics.

All 2 comments

@Andrew-Hanlon,

It's long, but you can read all the gory details of why the language design team chose to "enhance" the language in this way at #12939.

TL;DR you aren't alone in thinking the change unintuitive and contradictory to the way scope has always worked before. The team sadly don't care though and the change is here to stay.

@DavidArno - Thanks for the information and source!

I think this is a bad choice for the language, and I find it a shame that there is an assumptive justification around 'new keywords' being somehow worse than unintuitive and contradictory semantics.

Was this page helpful?
0 / 5 - 0 ratings