Question

i got the following code

screenshot

why has x in the finally-block the value 5 instead of beeing "already defined" or having the default value 0?

Was it helpful?

Solution 2

I guess you have set a breakpoint in the finally and looked at x. x has no value according to the C# language spec but the debugger probably looked at the storage location that the first x had and showed you its value.

In real code you would be unable to read from x in the finally.

The debugger does not obey the rules of the language.

OTHER TIPS

The lifetime of x is within {...} block, try in your case; however, since there's no zero-initialization of local variables in .Net the next x contains trash which is former x value

try
{
   int x = 5;
}
finally
{
   // x is re-declared; since x is local it contains trash;
   // former x was aquired at the stack, so .Net just moves stack pointer 
   // and doesn't remove former x value
   int x; 
   ...
}

http://msdn.microsoft.com/en-us/library/aa691170(v=vs.71).aspx

...A local variable is not automatically initialized and thus has no default value...

http://msdn.microsoft.com/en-us/library/aa664742(v=vs.71).aspx

...The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs...

You probably use visual studio debugger, that relays on variable names for values watch, and some how shows wrong value, in such messed up cases.

The scope of variable x is limited to try block only, yes Debugger shows the value 5 but if you try to use x variable you will face the problems you mentioned.

Try This:

finally
{
   int x;
   Console.Write(x); //error use of unassigned local variable
}

why has x in the finally-block the value 1 instead of being "already defined" or having the default value 0?

What you are seeing is the debugger linking up the symbols. It doesn't have a value at all, and in fact if you try and use it you get an unassigned variable error.

Now why doesn't it show as already defined is another question. The answer is that the {} define the declaration space. (In C# variables are defined at the branch level, not the function level). They are in two different declaration spaces and that's why it is allowed. The first x can't spill into where the second x is defined.

What you have is different than

void foo () {
 var x = 2;

 if (true){
   var x = 3;
 }

}

Which isn't allowed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top