Easily & safely disposing of objects with the C# using statement

As I’m sure everyone knows, you should always dispose of an object that you’ve created once you’re done using it. The most common way of doing this is using a try… finally block, where the object is disposed of in the finally block.
While there is absolutely nothing wrong with this, there is an easier way in C#; and that is to use a using block. Basically all the using block does is call Dispose on the IDisposable interface once the object referenced at the beginning of the using statement is out of scope.

So here’s how you would do it with a try… finally block:

bool isUnique = false;
SqlParameter[] parameters = new SqlParameter[1];
Utilities.Database database = new Utilities.Database();
SqlDataReader dataReader = null;

try
{
    parameters[0] = database.MakeInParam("@FieldName", SqlDbType.VarChar, 50, _name);
    dataReader = database.GetDataReader("Accounts.ExtraDetailsFieldExists", parameters);
    if (!dataReader.HasRows)
    {
        isUnique = true;
    }
}
finally
{
    if (dataReader != null)
    {
        dataReader.Close();
    }
    if (database != null)
    {
        database.Dispose();
    }
}

return isUnique;

And to do the same thing using the C# using block:

bool isUnique = false;

using (Utilities.Database database = new Utilities.Database())
{
    SqlParameter[] parameters = new SqlParameter[1];
    parameters[0] = database.MakeInParam("@FieldName", SqlDbType.VarChar, 50, _name);
	
    using (SqlDataReader dataReader = database.GetDataReader("Accounts.ExtraDetailsFieldExists", parameters))
    {
        if (!dataReader.HasRows)
        {
            isUnique = true;
        }
    }
}

return isUnique;

Isn’t that far more readable? Far less code and its very clear where the scope of each object ends. Now I hear you shouting what about closing the data reader! Luckily for us the base class of the SqlDataReader closes the data reader when Dispose is called, and the same applies to the SqlConnection class.