C# Using Statement

by Brad 26. April 2007 10:18

Instead of writing a try/catch/finally block for objects such as database connections, commands, streams (well anything that implements IDisposable) try to use the little known using command.

For example the following code works, but you'll notice that the connection and command are never closed and disposed, quite a simple mistake to make, but can prove costly!

SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cm = new SqlCommand
(commandString, cn);
cn.Open();
cm.ExecuteNonQuery();

The above can be easily replaced with the use of the using command...

using (SqlConnection cn = new SqlConnection(connectionString))
{
   
using (SqlCommand cm = new SqlCommand
(commandString, cn))
    {
        cn.Open();
        cm.ExecuteNonQuery();
   
}
}

So not only do you not have to remember to close your connections, but its much quicker to code, and much easier to read. using can be used for any object implementing IDispose (basically if it has a .Dispose() method!)

Tags:

C#

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar