2

I am trying to test this piece of code by putting in breakpoints. I want to make sure that after the using block the dispose method is called and the resources (SqlCommand), is gracefully released. However nowhere in the using block I hit any dispose?

    using (SqlCommand command = new SqlCommand(queryString, connection))
{
    command.CommandType = CommandType.Text;
    command.Parameters.Add("@OrganizationID", SqlDbType.Int);
    command.Parameters["@OrganizationID"].Value = organizationId;
    connection.Open();
    SqlDataReader sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

    try
    {
        while (sqlDataReader.Read())
        {
            //do something 
        }
    }
    finally
    {
        sqlDataReader.Close();
    }
}
1
  • 1
    nowhere in the using block I hit any dispose Can you explain this part in detail? Commented Aug 29, 2016 at 17:52

2 Answers 2

6

The call to Dispose of IDisposable happens after the using block has finished execution, normally or abnormally (i.e. through an exception).

The only way you could catch the call in a source-level debugger is when you have the source code for your IDisposable - in your case it would be the source code of SqlCommand class.

One simple way of checking the way this works is to make your own IDisposable implementation, put it into a using block, and observe its behavior. The call to Dispose should follow immediately after completion of the using block.

Sign up to request clarification or add additional context in comments.

Comments

3

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. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

Key part is the "achieve the same result by putting the object inside a try block and calling finally".

SqlCommand command = new SqlCommand(queryString, connection);
try {

      // your code here
} finally {

      command.Dispose();
}

From MSDN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.