c# - Ado.Net: Does closing SqlCommand cause closing DataReader -


today looked through legacy code , have began worrying. required close datareader explicitly.

my question is: closing sqlcommand close associated datareader well?

this code:

    using (var conn = new sqlconnection(this.connectionstring))     {         conn.open();          using (var cmd = conn.createcommand())         {             cmd.commandtype = commandtype.storedprocedure;             cmd.commandtext = "house_gethousebyid";              sqlcommandbuilder.deriveparameters(cmd);              cmd.parameters["@houseid"].value = houseid;              var reader = cmd.executereader())              while (reader.read())             {              }         }     } 

in snippet msdn command not closed explicitly:

string querystring =     "select orderid, customerid dbo.orders;";  using (sqlconnection connection =            new sqlconnection(connectionstring)) {     sqlcommand command =         new sqlcommand(querystring, connection);     connection.open();      sqldatareader reader = command.executereader();      // call read before accessing data.     while (reader.read())     {         console.writeline(string.format("{0}, {1}",             reader[0], reader[1]));     }      // call close when done reading.     reader.close(); } 

no. sqlcommand.dispose no-op¹, , won't close sqldatareader.

technically, closing sqlconnection should close resources, see question details:

however, bad practice -- relying on implementation detail of sqlclient library. "correct" way dispose (via dispose or using) idisposable. thus, code should written follows:

using (var conn = new sqlconnection(this.connectionstring)) {     conn.open();      using (var cmd = conn.createcommand())     {         cmd.commandtype = commandtype.storedprocedure;         cmd.commandtext = "house_gethousebyid";          sqlcommandbuilder.deriveparameters(cmd);          cmd.parameters["@houseid"].value = houseid;          using (var reader = cmd.executereader())         {             while (reader.read())             {                 //             }         }     } } 

¹ note not true command classes of other libraries such oledbcommand , sqlcecommand, don't in habit of not disposing commands.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -