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!)
4021b2f7-b283-4e6e-8584-3354d566c17d|0|.0
Tags:
C#