-
Is there an intentional difference in the scope of an I'm seeing a strange difference where if I declare a variable in i.e.: async Task DoWork()
{
while (!queue.TryTake(out var nextFile))
{
await Task.Delay(TimeSpan.FromMilliseconds(100));
}
MyBigBallOf(nextFile); // error CS0103: The name 'nextFile' does not exist in the current context
} Sharplab playground here. I would very much like for this to work without an error. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Yes, pattern variables and https://github.com/dotnet/csharplang/blob/master/meetings/2016/LDM-2016-11-30.md#scope-of-while-condition-expression-variables |
Beta Was this translation helpful? Give feedback.
Yes, pattern variables and
out
declarations within awhile
loop condition do not leak to the outer scope. This was an explicit decision based on the propensity that a capturing lambda within the loop body would enclose over the single leaked variable scope and not the value of the variable within the loop. That was a common source of confusion and bugs with capturing inforeach
loops to the extent that the team was willing to accept a breaking change to the language to resolve, so they didn't want to repeat that mistake.https://github.com/dotnet/csharplang/blob/master/meetings/2016/LDM-2016-11-30.md#scope-of-while-condition-expression-variables
dotnet/roslyn#15529