1

I have a ConcurrentStack<int>, and I'm doing this:

while (!stack.TryPop(out int res)) {
    
}
Console.WriteLine(res); // This doesn't work, res is not found

However, for some reason, the compiler can't find res. If I switch it to a simple if statement, it works:

if (!stack.TryPop(out int res)) {
    
}
Console.WriteLine(res); // Works

This seems quite odd, as the if syntax is almost the same as the while syntax.

I'm using C# 7.2.

  • 3
    The scope of `res` variable is only within the while loop, hence, compiler can't find it after the loop! – Am_I_Helpful May 03 '21 at 18:04
  • 2
    But that post doesn't answer the question? It is just about why the `if` statement works, but never mentions anything about the `while` loop. – IWatchCowsEat123 May 03 '21 at 18:19
  • 1
    @IWatchCowsEat123 duplicate shows `foreach` which behaves the same as `while` in that sense. Indeed `if` is behaving unexpectedly for most users of C#... If you just interested in "why scope of variable defined in for/foreach/while is limited to the body of the loop" you may want to ask separate question (also it would be likely duplicate too... which is not a bad thing by itself if question is reasonable like this one after all edits) – Alexei Levenkov May 03 '21 at 18:19
  • @IWatchCowsEat123 By default, a variable declared inside a code block has its scope limited to _that_ block. The case with `if` and an inline `out` variable declaration is just a special case as explained in the linked post. – 41686d6564 stands w. Palestine May 03 '21 at 18:19
  • @41686d6564 Oooh. So the `if` is just a special case but it doesn't apply to anything else? Even if the anything else uses a very similar out syntax? – IWatchCowsEat123 May 03 '21 at 18:21
  • 2
    @IWatchCowsEat123 yes, `if` is very special case (not just for `out`, but also for `x is Type varName`). Indeed it may feel opposite if you start with the version that allows such behavior. Note that pretty much every curly-brace strongly typed language behave that way ( you can't see loop variables outsude loop) and changing that would break a lot of code. – Alexei Levenkov May 03 '21 at 18:28
  • For more detail about scope of `out` arguments, see https://github.com/dotnet/roslyn/issues/16694. Also see https://web.archive.org/web/20190911112258/http://www.davidarno.org/2017/01/30/c-7-out-var-and-changing-variable-scope-revisited – Peter Duniho May 03 '21 at 18:36
  • Why would you ever do this anyway, you would normally use the `out` value within the braces only – Charlieface May 03 '21 at 20:44

1 Answers1

0

Just change the scope of the res variable.

int res;
while (!stack.TryPop(out res)) {
    
}
Console.WriteLine(res); // This works fine
g01d
  • 651
  • 5
  • 24