Can Of Code

Tag Archives: DataReader

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…” (unless your some kind of programming god!). 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 wizzy Database reading
}

Its the same as:

SqlDataReader reader = com.ExecuteReader();

 // Some wizzy 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

Posted in c#, Software | Tagged , , , , | Leave a comment