While debugging some C# code during a sort of peer-review, I noticed an odd behavior that seemed at first to be some sort of scoping violation, but in retrospect looks like perhaps the compiler attempting to save on memory by reusing references. The code is:
for(int i = 0; i < 10; i++)
{
// Yadda yadda, something happens here
}
// At this point, i is out of scope and is not
// accessible. This is verified by intellisense
// and by attempting to look at the variable
// during debug
string whatever = "";
// At this point if I put a break on the following
// for line, I can look at the variable I before
// it is initialized and see that it already holds
// the value of 10. If a different variable name
// is used, I get a value of 0 (not initialized).
for(int i = 0; i < 10; i++)
{
// Inside the loop, i has been re-initialized
// so it performs its function as expected
}
Is the compiler simply reusing an existing reference? In C/C++ where variables/references need to be managed more closely, this would be behavior I would sort of expect. With C# I was under the impression that each time a variable was declared within the scope of a loop that it would partition out a new separate section of memory, but obviously that’s not the case. Is this a memory saving feature, potentially a hold-over from C/C++ behaviors or is this case simply ignored since the compiler forces you to reinitialize anyway?
Edit:
Some things I’ve noticed in just doing some other checks is that this behavior is not exhibited across methods within a class. It does appear across multiple using statements, but only does this if the type and name are the same.
Upon further investigation, I’m beginning to believe this is less about the MISL code than it is about the IDE retaining these references in its own memory. I’ve seen nothing to indicate that this behavior would actually exist at the code level, and so now I’m leaning towards the idea that this is simply a quirk of the IDE.
Edit 2:
It looks like the answer from @Vijay Gill has disproved the IDE quirk.
It totally depends upon the compiler and what configuration you are using for compilation. In the following text dump, you can see that in Release mode, two int variables are declared where-as in dubug mode, only one.
Why it does so it totally beyond me (for the time being, I will investigate more when I go home)
Edit: See more findings near end of this answer
Release mode: (note the local variables i & V_1)
Debug Mode: (note the local variable i)
Assembly code generated is given below. This is for the IL compiled in Release mode only. Now even in the machine language (disassembled here) I see that two local variables are created. I could nto find any answer to that. Only MS guys can tell us. But this behaviour is very important to remember when we write recursive methods, in relation to the stack usage.