c# - Difference between initiating sql object inside "using" statement and decorating with using statement -


i've doubt significant difference applying "using" statement in same code block different way , know practice best way me sameple 1 code block

using (sqlconnection sqlconnection = new sqlconnection(dbconnectionstring))                  {                      sqlconnection.open();                      using (var command = new sqlcommand(store_procname, sqlconnection))                      {                          command.parameters.add(constants.param_value, sqldbtype.varchar).value = id;                          command.commandtype = commandtype.storedprocedure;                          using (var adp = new sqldataadapter(command))                          {                              adp.fill(dtvalid);                          }                      }                  }                  return dtvalid; 

sample code block 2

using (sqlconnection sqlconnection = new sqlconnection(dbconnectionstring))                  {                      sqlconnection.open();                      sqlcommand command = new sqlcommand(store_procname, sqlconnection);                                           command.parameters.add(constants.param_value, sqldbtype.varchar).value = id;                      command.commandtype = commandtype.storedprocedure;                      sqldataadapter adp = new sqldataadapter(command);                      adp.fill(dtvalid);                                          }                  return dtvalid; 

the using statement syntactical sugar release resources (eg memory or handles) without having write code yourself. code snippet like

using (var adp = new sqldataadapter(command)) {     adp.fill(dtvalid); } 

is converted like:

sqladapter adp = null; try {     adp = new sqldataadapter(command);     adp.fill(dtvalid); } {     if (adp != null) adp.dispose();     // or rather (adp idisposable)?.dispose(); } 

(this example give idea, not exact code generated compiler).

so if ommit inner using statements in code, dispose() methods of instances not called @ point. garbage collection clean objects (which leads calls dispose()).

the difference relevant if have lot of calls method , read lot of data sqlcommand , sqldataadapter consume lot of resources. if want release these resources possible, should include code in using statements.

you asking best practice (which matter of taste). in cases first snippet (with using statements) preferable, because releases resources no longer needed immediatly.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -