I'm trying to understand why y is in scope in the following example:
static void Main(string[] args)
{
int x = 1;
if (x is int y) { }
Console.WriteLine("This should NOT be in scope:" + y); // but it is...
}
If I change int x to object x, then y is no longer in scope (as expected).
Why is y in scope when the expression being matched is of int type and not when the type is object? It's odd that the scoping changes based on the expression type.
y seems to stay in scope when the expression type and the pattern type are the same, and they're both value types. (Same issue exists when both types are DateTime, but doesn't exist when they're both string).
(csc version is 2.0.0.61213.)
Update: It looks like y is in scope in both cases. In the object case, the compiler error is "Use of unassigned local variable 'y'." So it's not complaining about the variable being out of scope.
intbehavior (ybeing in scope) is correct. Andobjectbehavior is incorrect and should be fixed at a later release. Is that right? - Eren Ersönmezyinto the surrounding scope, even when unusable, is a good design decision. - David Arno