using statement

  • Thread starter Thread starter CSharper
  • Start date Start date
C

CSharper

I have a using statement something like the following

try
{
using(SqlConnection cnn = ...)
{
}
catch(Exception e1)
{
}

What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?
Thanks,
 
CSharper said:
try
{
using(SqlConnection cnn = ...)
{
}
catch(Exception e1)
{
}

What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?

Yes.
 
CSharper brought next idea :
I have a using statement something like the following

try
{
using(SqlConnection cnn = ...)
{
}
catch(Exception e1)
{
}

What happens to the sqlconnection, if the sql statment inside the
using statement fails? Will it close the sql connection since it is
inside the using?
Thanks,

Yes, the using statement is compiled similarly to

SqlConnection cnn = null;
try
{
cnn = ...;
// the "using block"
}
finally
{
if (cnn != null)
cnn.Dispose(); // which will close the connection
}

this does not "catch" any exceptions, so your own "catch" block can
handle them (but the connection is closed before your "catch" block is
activated).

Hans Kesting
 
CSharper brought next idea :




Yes, the using statement is compiled similarly to

 SqlConnection cnn = null;
 try
 {
   cnn = ...;
   // the "using block"
  }
  finally
  {
    if (cnn != null)
      cnn.Dispose(); // which will close the connection
  }

this does not "catch" any exceptions, so your own "catch" block can
handle them (but the connection is closed before your "catch" block is
activated).

Hans Kesting

Thanks both.
 
Back
Top