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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow