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 DataSet
is disposed when the using
block 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 using
block in this function. The using
block should be in the caller.
The ds
DataSet
will be disposed as soon as you leave the using
block, so you'll be returning a disposed DataSet
to the caller.
Why do you say that you can't call Dispose
on the DataSet
after you've returned it? I suspect that's exactly what you'll need to do.
Remove the using
block from your FlipDataSet
method and then dispose of the returned DataSet
in the calling code, preferably by wrapping it in a using
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With