c# - SqlCommand with using statement -


i saw in samples sqlcommand used this

using (sqlconnection con = new sqlconnection(cnn_string)) {     using (sqlcommand cmd = new sqlcommand("select id,name person", con))     {         sqldataadapter da = new sqldataadapter(cmd);         dataset ds = new dataset();         da.fill(ds);                    return ds;     } } 

i know why using "using" statement. sqlcommand doesn't inlcude close() method, should use within using statement

because implements idisposable.

the purpose of using statement when control reach end of using dispose object of using block , free memory. purpose not auto connection close, dispose connection object , connection closed due it.

its purpose free resources used inside using statement.

according msdn:

as rule, when use idisposable object, should declare , instantiate in using statement. using statement calls dispose method on object in correct way, , (when use shown earlier) causes object go out of scope dispose called. within using block, object read-only , cannot modified or reassigned.

the using statement ensures dispose called if exception occurs while calling methods on object. can achieve same result putting object inside try block , calling dispose in finally block; in fact, how using statement translated compiler. code example earlier expands following code @ compile time (note curly braces create limited scope object):

note:

you can instantiate resource object , pass variable using statement, not best practice. in case, object remains in scope after control leaves using block though no longer have access unmanaged resources. in other words, no longer initialized. if try use object outside using block, risk causing exception thrown. reason, better instantiate object in using statement , limit scope using block.


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -