kushal bhola kushal bhola - 7 months ago 23
C# Question

when does dispose method is called in using block

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;
SqlDataReader sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

while (sqlDataReader.Read())
//do something


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 {