Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lifetime of a variable in try finally

Tags:

c#

try-catch

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?

like image 832
fubo Avatar asked Mar 31 '14 14:03

fubo


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

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...

like image 128
Dmitry Bychenko Avatar answered Oct 26 '22 23:10

Dmitry Bychenko


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.

like image 22
usr Avatar answered Oct 26 '22 21:10

usr