Quick question re: DataSets

J

John Sweet

In the following code, is it OK to return the DataTable, or should I return
the DataSet so that it can be disposed in the calling code? In other words,
do I need to Dispose() a DataSet or will the framework clean it up for me?

public DataTable GetSomeData()
{
DataSet myDataSet = new DataSet();

// populate the dataset from SQL Server

return myDataSet.Tables[0];
}
 
C

Cor Ligthert

John,

When you real do it like this than looks for me a little bit crazy.
You are able to fill a datatable as well. Therefore why use a dataset.

The dataset will not be removed by the way even when you do a dispose.

In the way you do it now, there is a reference to the datatable that you
created. As long as that reference exist, than the dataset exist.

It will be probably be removed by the GC when that start running when you do
this. (When there are no more tables in it).

public DataTable GetSomeData()
{
DataSet myDataSet = new DataSet();
// populate the dataset from SQL Server
DataTable dt = myDataSet.Tables[0];
myDataSet.Tables.Remove[0];
return dt;
}

I hope this helps a little bit,

Cor
 
V

Val Mazur \(MVP\)

Hi,

If you dispose DataSet, then it will dispose DataTable as well. You should
not do anything here if you would like to return DataTable as a result of
function.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,225
Members
46,815
Latest member
treekmostly22

Latest Threads

Top