Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match variable scope

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));
}

Which shows the pattern match i variable used outside the if level scope of the pattern match.

Is this an oversight, or has the scoping been changed from the spec?

like image 920
Andrew Hanlon Avatar asked Nov 18 '16 15:11

Andrew Hanlon


People also ask

What is pattern matching give an example?

For example, x* matches any number of x characters, [0-9]* matches any number of digits, and . * matches any number of anything. A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested.

What is pattern matching in programming?

Pattern matching in computer science is the checking and locating of specific sequences of data of some pattern among raw data or a sequence of tokens. Unlike pattern recognition, the match has to be exact in the case of pattern matching.

Does C# have pattern matching?

C# pattern matching provides more concise syntax for testing expressions and taking action when an expression matches. The " is expression" supports pattern matching to test an expression and conditionally declare a new variable to the result of that expression.

What is pattern matching in C++?

Pattern matching in C++ is an alternative to using if statements to control the logic flow. Pattern matching lets you organize the code as matching patterns and the statements to be executed when the pattern match is found. You can think of pattern matching as a generalization of the switch-case statement in C and C++.


1 Answers

From that same documentation:

the variables introduced by a pattern – are similar to the out variables described earlier

So actually this code:

if (!(o is int i)) return; // type pattern "int i"

Is more or less equal to:

int i;
if (!(SomeParsingOn(o, out i))) return; // type pattern "int i"

That means that i is declared on the same level as the if, which means it is in scope not only for the if, but also for following statements. That this is true can be seens when you copy the if:

if (!(o is int i)) return; // type pattern "int i"
if (!(o is int i)) return; // type pattern "int i"

Gives error CS0128: A local variable named 'i' is already defined in this scope.

like image 175
Patrick Hofman Avatar answered Oct 11 '22 03:10

Patrick Hofman