C # using a keyword, using it correctly

which is better from the following options

Is it enough to use one operator?

Option 1:

using(SqlConnection con = new SqlConnection(constring))
{
   using(SqlCommand cmd = new SqlCommand())
   {
       .........................
       .........................
       .........................
   }
}

Option 2:

using(SqlConnection con = new SqlConnection(constring))
{
   SqlCommand cmd = new SqlCommand();
   .........................
   .........................
   .........................
}
+5
source share
5 answers

As a rule, it is easier to follow the rule: "If the type implements IDisposable, then use the construct using." So I would go in some form of option 1.

+15
source

You need to wrap them both, although you can make it look a bit neat if it bothers you!

using (var conn = new SqlConnection(/* ... */))
using (var cmd = new SqlCommand(/* ... */))
{
    // ...
}
+9
source

, , .

Connection Command, , , .

.

+2

, , , , IDisposable.

+1

It is better to use two commands (although there are alternative syntaxes ) when you have multiples. It’s best to be explicit when you want to access these resources.

+1
source

All Articles