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?
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.
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.
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.
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++.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With