Is there any difference between these two code?

  • Thread starter Thread starter Nick
  • Start date Start date
N

Nick

hi, all
I am just wondering if there is some difference between these two code:
I:
using(SqlDbConnection con = new .....)
{
SqlDbCommand cmd = new SqlDbCommand(strQuery, con);
cmd.ExecuteNonQuery();
}
Once the program exit the using }, the con should be disposed.

II:
SqlDbConnection con = null;
using(con = new .....)
{
SqlDbCommand cmd = new SqlDbCommand(strQuery, con);
cmd.ExecuteNonQuery();
}
Here, will it do the same thing as I? It might think there is still a
reference.
 
Nick,
There is no difference between the two. In both cases, the objects are
disposed of when the } is hit.

HTH,
S.M. Altaf
[MVP - VB]
 
S.M. is correct, both objects are disposed of when the using block ends. I
would like to add though that the difference is that you do have a reference
to an disposed of object at the end of the second example, a reference that
will never turn null on it’s own and trying to use it can be dangerous...
even though it is still accessible.

As an example, throw in Console.WriteLine( con.WorkstationId ) at the end of
the second using block and you should see your workstation id/name returned
from this disposed of object.

Brendan
 
Something I like more, since SqlCommand also needs disposing (ok, it has a
Dispose() method...) is the following:

using(SqlConnection conn = new ...)
using(SqlCommand cmd = conn.CreateCommand())
{
...
}

That way (i) the command is created from the connection and both are
disposed at the proper time and (ii) no references are left to disposed
objects (as another reply mentioned.

my 2cents
scott
 
Hi,

As the other posters stated both forms are valid and in both cases the
object is disposed , now I highly recommend you do not use the second
version, you expose the variable out of the scope of the using, and up to
the method. This may cause problems:


SqlDbConnection con = null;
using(con = new .....)
{
SqlDbCommand cmd = new SqlDbCommand(strQuery, con);
cmd.ExecuteNonQuery();
}
cmd.ExecuteScalar(); // will give you error

The first variant will cause a compiler error in that line.


you should always declare the variable in the using statement, IIRC Fxcop
will gives you a warning in this situation.

Cheers,
 
Back
Top