Reputation: 75
I read many threads about the using
keyword in C#, but I couldn't find anyone with the same question.
Reading this interesting article, it says that the using statement is basically equivalent to a try/catch block:
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes!= null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
What really makes me going mad is that the object initialization myRes= new MyResource()
is still outside of the try/catch block, so if something goes wrong during the initialization (oh, and it does!) I have no other way to handle it than using a normal try/catch block.
Is this correct or am I missing something? In my opinion, this makes the sense of the using
statement partially useless.
I also tried something like this:
using (MyResource myRes)
{
myRes = new MyResource();
myRes.DoSomething();
}
but the compiler don't like this, so it is not possible to bring the initialization inside of the try block.
This seems so strange to me that I think that I must be missing something. Could anyone explain me the reasons behind this?
Upvotes: 1
Views: 398
Reputation: 1503230
Well if the constructor fails, the exception will be thrown instead of the reference being returned - so the calling code has nothing to dispose.
Basically, constructors need to be careful. If an exception is thrown in an exception, the constructor needs to make sure no resources are leaked, because nothing else is going to get a chance to clean up.
Upvotes: 3