Reputation: 3
I have a legacy system that I have noticed the following code in
var dataTable = new DataTable();
using(var connection = new SqlConnection())
using(var command = connection.CreateCommand())
{
command.commandType = CommandType.StoredProcedure;
//Attach command parameters etc.
var reader = command.ExecuteReader();
dataTable.Load(reader);
}
return dataTable;
Normally I would wrap the data reader into a using statement so the lines would read:
using(var reader = command.ExecuteReader())
{
dataTable.Load(reader);
}
I think that I'll schedule the time in to update these methods to include a using statement for the data reader as well, but I was wondering whether anyone knew whether, in the instance above, the datareader will get disposed of when the command or connection is disposed of anyway?
Upvotes: 0
Views: 271
Reputation: 157038
You have to do it yourself, since the command doesn't clear up the DataReader
for you. See as an example SqlCommand.Dispose
.
It is save in this situation to use a using
since DataTable.Load
doesn't keep a reference to the DataReader
used. As a proof of that, see the reference source of DataTable
.
Upvotes: 1