0

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?

1 Answer 1

1

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.

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

2 Comments

Okay - unfortunately that doesn't actually answer the question asked by the OP, namely whether the DataReader will already be disposed when the command/connection is disposed.
Yup. Admittedly it's hard to tell what the impact of not disposing of the reader will be, but that's slightly different anyway.

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.