Should I Dispose() DataSet and DataTable?

mbeckish picture mbeckish · May 27, 2009 · Viewed 100.2k times · Source

DataSet and DataTable both implement IDisposable, so, by conventional best practices, I should call their Dispose() methods.

However, from what I've read so far, DataSet and DataTable don't actually have any unmanaged resources, so Dispose() doesn't actually do much.

Plus, I can't just use using(DataSet myDataSet...) because DataSet has a collection of DataTables.

So, to be safe, I'd need to iterate through myDataSet.Tables, dispose of each of the DataTables, then dispose of the DataSet.

So, is it worth the hassle to call Dispose() on all of my DataSets and DataTables?

Addendum:

For those of you who think that DataSet should be disposed: In general, the pattern for disposing is to use using or try..finally, because you want to guarantee that Dispose() will be called.

However, this gets ugly real fast for a collection. For example, what do you do if one of the calls to Dispose() thrown an exception? Do you swallow it (which is "bad") so that you can continue on to dispose the next element?

Or, do you suggest that I just call myDataSet.Dispose(), and forget about disposing the DataTables in myDataSet.Tables?

Answer

DOK picture DOK · May 27, 2009

Here are a couple of discussions explaining why Dispose is not necessary for a DataSet.

To Dispose or Not to Dispose ?:

The Dispose method in DataSet exists ONLY because of side effect of inheritance-- in other words, it doesn't actually do anything useful in the finalization.

Should Dispose be called on DataTable and DataSet objects? includes some explanation from an MVP:

The system.data namespace (ADONET) does not contain unmanaged resources. Therefore there is no need to dispose any of those as long as you have not added yourself something special to it.

Understanding the Dispose method and datasets? has a with comment from authority Scott Allen:

In pratice we rarely Dispose a DataSet because it offers little benefit"

So, the consensus there is that there is currently no good reason to call Dispose on a DataSet.