C# Quick Tip 1 – The Using statement
If you have ever dealt with C# enough to hook up to a database and use a DataReader you would of properly seen a Exception along the lines of “There is already an open DataReader associated with…”. You would get this exception because you had forgot to close a previous DataReader somewhere, annoying right?
Well I had this problem a little while ago but it was happening because an exception was getting thrown which meant it skipped right past my .Close() call. It was at this point I found out about the joyous using statement.
So Here it is:
using (SqlDataReader reader = com.ExecuteReader()) { // Some Database reading }
Its the same as:
SqlDataReader reader = com.ExecuteReader(); // Some Database reading reader.Close();
But… In the second example, if the code is within a Try..Catch and the wizzy database reading code throws an exception. it will miss the .Close() statement and then you’ve got to go and find out why. The first example will automatically close the reader as soon as it leaves the block! which save you the pain! and I think it looks much cleaner then having .Close() statements everywhere.
If you enjoy reading the MSDN site here is a link to the using statements page