Question

Ok, this is trivial but its been bugging me. I have code something like this

oCmd = new SqlCommand("getBooking", oCon); 
oCmd.CommandType = CommandType.StoredProcedure;
oRs = oCmd.ExecuteReader();
do while (oRs.Read()) {
    // do stuff
}
oRs.Close();
oCmd.Dispose();

But can I move the Dispose to after the ExecuteReader like this:

oCmd = new SqlCommand("getBooking", oCon); 
oCmd.CommandType = CommandType.StoredProcedure;
oRs = oCmd.ExecuteReader();
oCmd.Dispose();
do while (oRs.Read()) {
    // do stuff
}
oRs.Close();

I've tried it, it works but it feels like I'm being naughty. Is there a gotcha with this approach? I ask because there is often a need to re-use the SqlCommand object within the do while, and no I don't want to create multiple SqlCommand objects.

Was it helpful?

Solution 2

While it does work in this case you probably shouldn't dispose of it until you are done with the reader that you requested from it.

While in this case you know that the implementation of SqlReader does not make use of the SqlCommand object that created it, this does not hold true for all cases. It is much better not to make assumptions about the implementation of a class.

In this case I would also suggest that you use using or try/finally statements because if an exception is thrown anywhere in your code as it is currently written you will not dispose of the sql objects.

OTHER TIPS

Yes, it's best to dispose of the objects as soon as you're done with them. There's really no advantage in reusing commands and your code may get complicated and harder to understand and maintain because of that.

It's best to use the using syntax for it:

using (var oCmd = new SqlCommand("getBooking", oCon))
{
    oCmd.CommandType = CommandType.StoredProcedure;
    using (var oRs = oCmd.ExecuteReader())
    {        
        while (oRs.Read()) {
            // do stuff
        }
    }
}

When you use using on a disposable object (implementing IDisposable), Dispose method will call Close. You can do the same for your SqlConnection.

Whenever you are using "using block" then no need of connection.close or connection.dispose. As per CA2202, we should not dispose objects more than once

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top