Search code examples
c#asp.netdisposesqlcommand

Do I have to Dispose a SqlCommand after its recordset is closed?


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.


Solution

  • 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.