Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How C# Using Statement Translates to Try-Finally

I'm trying to wrap my head around this. According to this page on Using statements:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

But on this page about Try-Finally blocks it states:

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.

So how can a Using statement be guaranteed to call the Dispose method in the event of an exception if it translates to a Try-Finally that is not guaranteed to call the finally statement?

like image 888
TrueEddie Avatar asked Feb 02 '16 19:02

TrueEddie


People also ask

How do C codes work?

c is called the source file which keeps the code of the program. Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no error, then it stores the file as a . obj file of the same name, called the object file.

What is C full explanation?

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

How is C created?

The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson, incorporating several ideas from colleagues. Eventually, they decided to port the operating system to a PDP-11.


2 Answers

It really does behave like a try/finally - so if the application terminates, the resource may not be disposed... and that's usually okay, because normally disposal is for releasing resources held by the process... and the OS will tidy those up anyway on process death. (That's not to say the Dispose method won't be called... it's just the same as with a normal try/finally.)

Obviously if you've got a "lock file" on the file system or something like that, that would be a problem - but you'd have the same problem in the face of a power cut etc.

like image 95
Jon Skeet Avatar answered Sep 29 '22 11:09

Jon Skeet


There are exceptions from which a program can't recover, in that case finally block will not execute. For example Stack overflow exception or Out of memory exception.

like image 28
Habib Avatar answered Sep 29 '22 10:09

Habib