A question I’m asked from time to time is why and when should I use a using statement within my code.
For me, using statements are all about convenience. They provide a nice simple way of ensuring that I am using IDisposable objects correctly, plus I also like tidy code. What’s an IDisposable object? It’s an object which implementes the IDisposable interface, which from a coding perspective means that you have access to a .Dispose() method e.g.
DataTable dt = MethodWhichReturnsAPopulatedDataTable(); // Loop through the rows in the DataTable and output the column "ColumnName" foreach (DataRow row in dt.Rows) { Console.Writeline(row["ColumnName"].ToString()); } dt.Dispose();
What’s the point of IDisposable? Well, basically it ensures that your object correctly disposes of any unmanaged resources immediately (even when an exception occurs), rather than waiting on the garbage collector. Plus when used with a SqlConnection object, the connection will be closed and disposed off if created via a using statement. For more information, on IDisposable, check out this article on msdn.
Okay, so, back to the original purpose of this post which is to cover the use of the using statement.
So, the code example above showed a DataTable object being created and disposed of which is all very well you might think but what if a) I forgot to put make a call to .Dispose() or b) I put the .Dispose() method in but an exception occurred before that line of code was reached? Well, in both cases the DataTable would continue to consume resources until the garbage collector came along and freed those up.
That’s where the using statement comes into its own. When you wrap your object within a using statement the .Net compiler knows to automatically dispose of the object when the closing } is reached, meaning you don’t need to remember to call the .Dispose() method. In addition, if an exception occurs within your using statement code block, the compiler will still dispose of your object correctly. Okay, okay, you could achieve the same result by wrapping the use of the IDisposable object within a try catch block and calling .Dispose() in the finally part but that’s a lot more typing.
So, how would I rewrite the above code block within a using statement? Easy:
using (DataTable dt = MethodWhichReturnsAPopulatedDataTable()) { // Loop through the rows in the DataTable and output the column "ColumnName" foreach (DataRow row in dt.Rows) { Console.Writeline(row["ColumnName"].ToString()); } }
Oh and as a general rule Microsoft suggest that any objects which implement IDisposable should be wrapped up in a using statement and, well, who am I to disagree.
For more information this msdn article should help.