views:

155

answers:

2

I'm going through some old C#.NET code in an ASP.NET application making sure that all SqlConnections are wrapped in using blocks.

This piece of code used to open cn and da and close and dispose them in both the catch block and the end of the method. I added the usings and can't figure out for certain if the using blocks still handle disposing of the connection if an exception is thrown in the try and caught in the catch. This question seems to suggest that it does.

using (SqlConnection cn = new SqlConnection(Global.sDSN))
{
    using (SqlDataAdapter da = new SqlDataAdapter())
    {
        // do some stuff
        try
        {
            // do stuff that might throw exceptions
        }
        catch (catch (System.Exception e)
        {
            //return something here
            // can I ditch these because the using's handle it?      
            da.Dispose();
            cn.Close();
            cn.Dispose();
            return msg;
        }
    }
} 
+4  A: 

Yes, they will. They're basically turned into a finally block.

So something like this:

using (SqlConnection cn = new SqlConnection(Global.sDSN))
{
....
}

is really turned into:

SqlConnection cn = new SqlConnection(Global.sDSN)
try
{
....
}
finally
{
    cn.Dispose();
}

more or less - and the finally block is always executed, no matter what might have happened before in the try {.....} block.

marc_s
+2  A: 

When you use a using clause this is what's happening:

myobject = new object();
try{ 
   // do something with myobject
}finally{
   myobject.Dispose();
}

Hope this helps, Best regards, Tom.

tommieb75