In General
You should Dispose
every class that implements IDisposable
.
However, your question is specifically dealing with a scenario where all the resources are all related, which if my understanding is correct, the Garbage Collector will dispose these resources for you automatically.
The Finalize()
Method ("Destructors" or "Finalizers")
The Finalize()
method makes sure that resources are disposed when
the instance is no longer referenced by the application.
In concert together with the Dispose()
method
The Dispose()
method will "release all resources used by the component". Which would mean that this code block (taken from MSDN's ExecuteReader Method Example) will properly dispose of all the compenents used by it...
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// ...
}
}
In this case, when disposing SqlConnection
, it will properly
release all resources used by the component. Which means:
Refactoring of the above code to the following:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// ...
}
}
}
}
The main advantage of manually disposing of each resource, would be
for a performance gain since we are not processing up to the
Finalize
method (which is relatively a more expensive than doing Dispose()
.
However, that doesn't mean you want to Dispose()
everything, as in some cases the Finalize()
method is a better choice.
Assuming that I am still in good shape so far, and my understanding of the Garbage Collector's behavior is valid.
I would consider that SqlCommand
(full code reference here), would then also dispose of SqlReader
, which would mean that you could just get away with:
using (SqlCommand command = new SqlCommand(queryString, connection))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// ...
}
}
which in your case would translate to:
using (var cmd = data.CreateCommand(sql))
{
var reader = cmd.ExecuteDataReader();
// ...
}