I have a C# function that flips the orientation of a DataSet:
static DataSet FlipDataSet(DataSet my_DataSet)
{
using (DataSet ds = new DataSet())
{
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow r = null;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
r[j] = dt.Rows[j - 1][k];
table.Rows.Add(r);
}
ds.Tables.Add(table);
table.Dispose();
}
return ds;
}
}
I modified this code from a snippet I found on the interwebs to wrap the created DataSet in a using statement and explicitly dispose of the IDisposable objects it creates. My question is, what happens to the DataSet (“ds” in the above code) when it is returned, in terms of disposal? I cannot explicitly call .Dispose() on ds after I return it, obviously, so does .NET return the value and then dispose of it properly, or am I missing something entirely?
You probably don’t want to do this. The
DataSetis disposed when theusingblock exits regardless of how the block exits (normal exit, return, or thrown exception), meaning that the value you return will have been disposed and be mostly unusable to the caller.The right thing to do is to not have a
usingblock in this function. Theusingblock should be in the caller.