Monday, April 14, 2008

using Statement

With a using statement, your objects will dispose of themselves once out of scope of the using statement block. For example, you ever open a file or open a connection to a database and then at the end close your connection? The using statement can do this for you.
Before:
SqlConnection conn = null;
SqlCommand cmd = null;

try
{
    conn = new SqlConnection(connString);
    cmd = new SqlCommand(commandString, conn);

    conn.Open();
    cmd.ExecuteNonQuery();
}
finally
{
    if (cmd != null)
        cmd.Dispose();
    if (conn != null)
        conn.Dispose();
}
After:
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand cmd = new SqlCommand(commandString, conn))
    {
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}
Can I do this with any object?
In order to use using, the object has to implement IDisposable. Notice the SqlConnection class:

IDisposable only has one method, "Dispose()". The implemented Dispose method on the IDisposable interface will get called as soon as execution leaves the using code block.
This is pretty interesting. Can you think of any of your classes where you have to perform some cleanup when done? You could implement IDisposable and then use your classes in using statements.

More Info: MSDN: using Statement