C # try lifetime of a variable in try finally

I got the following code

screenshot

Why is x in the finally block value 5 instead of beeing "already defined" or has a default value of 0?

+6
source share
5 answers

I think you set a breakpoint in finally and looked at x . x does not matter according to the C # language specification, but the debugger probably looked at the storage location that the first x and showed you its value.

In real code, you cannot read x in finally .

The debugger does not obey the rules of the language.

+5
source

The lifetime x is in the block {...} , try in your case; however, since there is no zero initialization of local variables in .Net, the next x contains garbage, which is the old value of x

 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 initialized automatically and therefore does not have a default value ...

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

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

+7
source

You are probably using a visual studio debugger that relays variable names to view values, and some as an incorrect value in such ruined cases.

+1
source

The scope of the variable x limited only by the try block, yes Debugger shows the value 5, but if you try to use the variable x , you will encounter the problems you were talking about.

Try the following:

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

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

What you see is a debugger connecting characters. It does not matter at all, and in fact, if you try to use it, you will get an unrecognized variable error.

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

What you have is different from

 void foo () { var x = 2; if (true){ var x = 3; } } 

It is unacceptable.

0
source

All Articles