Home > Back-end >  Difference in variable scope between C/C and C# or a quirk in the debugger?
Difference in variable scope between C/C and C# or a quirk in the debugger?

Time:02-28

I have solved this issue already by replacing the second variable's name, hence this is a low priority question, but I'd like to understand what happens.

I have this situation in my C#-code (value of the variable 'list' is "V3"):

foreach (string entry in list.Split()){                   // Loop1
    ...
}

string [] list_statuses = { "V1", "V2", "V3", "V4", ...};
foreach (string entry in list_statuses) {                 // Loop2
    ...
}

I was expecting the following behaviour:

  1. In Loop1, the variable 'entry' only gets value "V3", the loop is run once and finishes.
  2. In Loop2, the variable 'entry' gets values "V1", "V2", "V3", ..., the loop is run all those times and finishes.

Important remark: the variable 'entry' in Loop1 is not the same than the variable 'entry' in Loop2:
The scope of 'entry' in Loop1 is restricted to Loop1, and a completely new variable, allbeit with the same name, is used in Loop2.

To my surprise, while debugging this, in Loop2 that variable gets the value "V3" different times, as if C# does not take into account the scope of that variable as expected.
While changing the name of the second variable, the problem is solved, but I would like to understand what's happening here:
My understanding of variable scope comes from the C/C language. Is the observed behaviour a bug or is there a difference in variable scope between C# and C/C ?

Oh, in case this is a problem in the debugger: I'm working with Visual Studio Enterprise 2017, version 15.9.44.

CodePudding user response:

It's a quirk in the debugger:
When I check the value in the debugger, the value seems to be wrong.
When I print it on screen, the value seems to be correct.

For obvious reasons, I always obfuscate my code in order to hide my source code and to create a so-called minimal and reproducible example. But in this case it seems to be impossible: when I insert the code from this question in my program, everything seems to be ok.

I believe this question can be closed, stating that, in case the C# debugger in Visual Studio seems not to work correctly with variables' scope, this might be due to some weird debugger bug. In such a case, I would advise:

  • Either to check the real behaviour (using logs)
  • Either to use different variable names, in order to avoid the issue.
  • Related