By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,467 Members | 1,500 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,467 IT Pros & Developers. It's quick & easy.

using() statement will it call dispose when return is called

P: n/a
LP
Hi,
Considering the following code:

using(mySQLconn)
{

if (someCondition==true)
return 0;
//more code after return
//do some db calls
}

return 1;
Will .mySQLconn.Dispose(); still be invoked even when return is called?
Thank you
Nov 16 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Actaully, Dispose should be called when the code block for USING ends, which
is before your "return" statement.

"LP" <lp@a.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
Hi,
Considering the following code:

using(mySQLconn)
{

if (someCondition==true)
return 0;
//more code after return
//do some db calls
}

return 1;
Will .mySQLconn.Dispose(); still be invoked even when return is called?
Thank you

Nov 16 '05 #2

P: n/a
LP,
The short answer is "yes". The using statment is the same as:
try{
// do something with the connection
// maybe return
}finally{
mySQLconn.Dispose();
}

No matter what, Dispose() will be called. . . and because of the
implementation of the Dispose() method on SqlConnection, Close() is
called from within the Dispose() method.

Best regards,
Jeffrey Palermo
Blog: http://www.jeffreypalermo.com

Nov 16 '05 #3

P: n/a

"Peter Rilling" <pe***@nospam.rilling.net> a écrit dans le message de news:
Oa**************@TK2MSFTNGP15.phx.gbl...
Actaully, Dispose should be called when the code block for USING ends,
which is before your "return" statement.
This is misleading. If your return statement is
return expression;
then the expression is evaluated "before" Dispose() gets invoked.

The big plus of "using" is that it guarantees that Dispose will be called
regardless of how the block terminates (after the last statement of the
block, via a return, break or continue, or via an exception). It is a short
cut for a try { ... } finally { resource.Dispose(); } as already mentioned.

Bruno.

"LP" <lp@a.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
Hi,
Considering the following code:

using(mySQLconn)
{

if (someCondition==true)
return 0;
//more code after return
//do some db calls
}

return 1;
Will .mySQLconn.Dispose(); still be invoked even when return is called?
Thank you


Nov 16 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.