Using the ‘using’ keywork in C#

C# Super HeroIn the System.Data.SqlClient namespace, SqlConnection and SqlCommand are two examples of managed types that use unmanaged resources down in the COM layer of the run-time. Microsoft says that all of these types must implement the IDisposable interface.

Also from Microsoft:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and …it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

using (SqlConnection conn)
//do work

The using statement ensures that Dispose is called even if an exception occurs. This is the same as wrapping it in a try/finally block:

SqlConnection conn;
    conn = GetConnection();
    // do work

What I like to do is to nest my SqlClient objects in using statements:

string sqlString = "select * from myTable";
using (SqlConnection conn = GetConnection())
    using (SqlCommand cmd = new SqlCommand(sqlString, conn))
        // do work, like add params, execute the statement
        // read the results, etc

        // even if you return from inside this nested using statement
        // both the cmd and conn objects are disposed properly    } // cleans up cmd
} // cleans up conn

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s