I have the following code.
private DataTable LoadSMSCellProviders()
{
string sqlQuery = "Select * from SMSAddress";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(Utility.ConnString))
{
using (SqlCommand command = new SqlCommand(sqlQuery, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
return dt;
}
}
}
The Microsoft Code Analysis is telling me that dt
is not disposed along all execution paths, but I am not sure how to correct this. If I try to call dispose
on it before the return
, it will return a null value, and if I try to do it at the end of the method, the code is never reached...
What am I missing here?
This is the message from the analysis tool:
warning : CA2000 : Microsoft.Reliability : In method 'x.x()', object 'dt' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'dt' before all references to it are out of scope.
You need to dispose of it when an exception occurs. Like this.
private DataTable LoadSMSCellProviders()
{
string sqlQuery = "Select * from SMSAddress";
DataTable dt = null;
try
{
dt = new DataTable();
using (SqlConnection conn = new SqlConnection(Utility.ConnString))
{
using (SqlCommand command = new SqlCommand(sqlQuery, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
return dt;
}
}
}
catch
{
if(dt != null)
dt.Dispose();
throw;
}
}
The idea is that if an exception occurs then there is no way to dispose of the DataTable
because it will not be passed back to the caller. So, this is the pattern that will make code analysis happy.
Fire the tool. DataTables do not need to be disposed. They are IDisposable because they inherit IComponent, but their Dispose() method does nothing. I find it disgusting that MS's own tool does not know this.
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