I have a function that fills a DataTable using a SqlDataAdapter
// ...
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
try
{
dataAdapter.Fill(dataTable);
}
catch
{
dataTable.Dispose();
dataTable = null;
}
Now, I dislike cargo-cult programming, so I would rather not have a try–catch block if it is unnecessary. Is it necessary to Dispose a DataTable that fails to get filled?
No, calling
Disposeis not required. Doing so will not deallocate the memory that has been used for the object, and the GC will pick it up at a later point even if you don’t callDispose. You can read more about this here.