Thursday, May 1, 2008

The C# using statement

In C#, when you want to make sure an object is disposed, then you might place you're code within a try finally block as follows:
SqlCommand command = new SqlCommand();
try
{
 command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
 command.CommandText = "delete from dbo.Customer;";
 command.Connection.Open();
 command.ExecuteNonQuery();
}
finally
{
 command.Dispose();
}
However, a nicer and shorter way of writing the exact same code is by using the using statement as follows:
using (SqlCommand command = new SqlCommand())
{
 command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
 command.CommandText = "delete from dbo.Customer;";
 command.Connection.Open();
 command.ExecuteNonQuery();
}
The using block will only work with objects of classes implementing the IDispose interface. In the case of the SqlCommand used in the code above, the Dispose method closes the database connection if it's open and clears any resources used.