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

  • Thread starter Thread starter LP
  • Start date Start date
L

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
 
Actaully, Dispose should be called when the code block for USING ends, which
is before your "return" statement.
 
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
 
Peter Rilling said:
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.
 
Back
Top