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:
- In Loop1, the variable 'entry' only gets value "V3", the loop is run once and finishes.
- 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.