Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is not disposed along all execution paths

Tags:

c#

c#-4.0

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.

like image 881
Brad Avatar asked Nov 14 '14 16:11

Brad


2 Answers

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.

like image 158
juharr Avatar answered Sep 30 '22 21:09

juharr


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.

like image 22
Joshua Avatar answered Sep 30 '22 19:09

Joshua