I have code that creates a DataTable
and returns it, like this:
public static DataTable Transpose(DataTable input)
{
DataTable transpose = new DataTable();
// first column name remains unchanged
transpose.Columns.Add(input.Columns[0].ColumnName);
for (int i = 1; i < input.Columns.Count; i++)
{
// all other column names become first row
transpose.Rows.Add(new object[] { input.Columns[i].ColumnName });
}
for (int j = 0; j < input.Rows.Count; j++)
{
// all row values in column 0 are now column names
transpose.Columns.Add(input.Rows[j][0].ToString());
for (int i = 1; i < input.Columns.Count; i++)
{
transpose.Rows[i - 1][j + 1] = input.Rows[j][i].ToString();
}
}
return transpose;
}
I get this warning on Code Analysis: CA2000: Dispose objects before losing scope
Of course the warning is easily fixed by using a using
:
public static DataTable Transpose(DataTable input)
{
using(DataTable transpose = new DataTable())
{
// same stuff here
return transpose;
}
}
But why?
(a) Why's the original code throwing the warning?
(b) Is it safe to return the variable declared within using
, from inside the using
block?