Thursday, July 7, 2011

C# "using" statement - a small caveat

I was thinking the "using" statement will always ensure the enveloped object is disposed safely. And it does so except in one scenario. When an error occurs in the constructor of the enveloped object, the dispose method is not at all called.

I have read in many sites that

using (ConcreteDispose c = new ConcreteDispose())
{
   c.yourMethod();
}

roughly transalates to

ConcreteDispose c = new ConcreteDispose ();
try
{
   c.yourMethod();
}
finally
{
  c.Dispose();
}

After looking into the above code snippet again, it dawned on me that this issue is because finally block will not be exectued (when exception is thrown in the constructor) as the instance is created before the try block. I thought this could be easily solved if the translated code is something like below

ConcreteDispose c;

try
{
   c = new ConcreteDispose ();
   c.yourMethod();
}
finally
{
  if (c != null) 
    c.Dispose();
}

This will exectue the finally clause but the instance is not created (when constructor throws exception) and so the dispose method will not be called at all.

Although doing too much work in the constructor is not recommended, but if you are doing it for some reason then keep this in mind....

Happy coding :-)

2 comments:

Anonymous said...

expectpion -> Exception
:)

Bala said...

Corrected the typo. Thanks!!

Post a Comment