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!)


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Thursday, April 26, 2007 11:18 AM | in C#

Comments

No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 6 and 7 and type the answer here: