Search code examples
c#using-statement

What happens to the objects created inside a using statement?


I have been trying to search for this and could not find an answer, May be I was not looking at the right places so please bear with me...

Question:

I know that a using statement calls the dispose method of the object, for example:

using (SqlConnection conn = new SqlConnection(conString))
{
    // some work
} 
// dispose method for this connection object will be called must.

But what happens to the objects created inside this using statement?

using (SqlConnection conn = new SqlConnection(conString))
{
    SqlCommand cmd = new SqlCommand(query, conn);
    // some work
}      

Will the dispose method of command object be also called? Or should I do this instead:

using (SqlConnection conn = new SqlConnection(conString))
{
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        //some work
    }
    // some work
}

Which is the best practice and which one will be more efficient ?


Solution

  • Will the dispose method of command object be also called?

    No

    Or should I do this instead:

    Yes

    Which is the best practice and which one will be more efficient ?

    The one that works - the last one. Note you can avoid "heading right" on the page:

    using (SqlConnection conn = new SqlConnection(conString))
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        // some work
    }
    

    I'm too lazy to use ADO.NET directly; another option is to get a tool to handle everything except the connection (example shown is "dapper", but other tools exist):

    using (SqlConnection conn = new SqlConnection(conString))
    {
        var data = conn.Query<SomeType>(someSql, new { foo, bar }).ToList();
                        // where @foo and @bar are parameters in the sql
    }
    

    then you don't need to worry about the command, data-reader, parameters, etc.