MiBol
MiBol

Reputation: 2125

How should I correctly dispose of an object?

I frequently use the following code (or alike) to dispose of objects:

SqlCommand vCmd = null;

try 
{
    // CODE
}
catch(Exception ex) { /* EXCEPTION HANDLE */ }
finally 
{
    if (vCmd != null) 
    {
        vCmd.Dispose();
        vCmd = null;
    }
}

Is this the best way to release objects and dispose of objects?

I'm using the VS analytics and give me a warning about redundancies. But I always do it this way...

Upvotes: 2

Views: 118

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460380

The best way in terms of readability is using the using statement:

using(SqlCommand vCmd = new SqlCommand("...", connection)
{
    try 
    {
        // CODE
    }
    catch(Exception ex) 
    { 
        // EXCEPTION HANDLE
    }
}

It disposes objects even in case of error, so similar to a finally. You should use it always when an object implements IDisposable which indicates that it uses unmanaged resources.

Further reading:

Upvotes: 4

paulsm4
paulsm4

Reputation: 121881

Here is an example from MSDN:

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

Note the use of "using" for the connection.

Back in the Olden Days of COM/ActiveX, you needed to set your objects to "Nothing".

In managed code, this is no longer necessary.

You should neither call "Dispose()", nor set your sqlCommand to "null".

Just stop using it - and trust the .Net garbage collector to do the rest.

Upvotes: 1

Related Questions