In my below function...I want to return DataTable..
Should I convert the below line
DataTable table = CreateTable<T>();
to following
using(DataTable table = CreateTable<T>())
{
}
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
int iColCount = table.Columns.Count;
for (int j = 0; j < iColCount; j++)
{
DataColumn myDC = table.Columns[j];
myDC.DataType = System.Type.GetType("System.String");
}
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
} table.Rows.Add(row);
}
return table;
}
Why would you?
using (obj)
{
// Do something
}
is basically the same as:
try
{
// Do something
}
finally
{
obj.Dispose();
}
The point is to free the resources used by your object once you don't need it anymore. In your case, you're returning the datatable to the calling function, so you're still going to need it. Therefore, there's no reason to wrap your function inside of a using
statement.