5

which one is better from following options

Is one using statement is enough?

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();
   .........................
   .........................
   .........................
}
frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
Ali
  • 3,545
  • 11
  • 44
  • 63
  • possible duplicate of [Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?](http://stackoverflow.com/questions/1808036/is-sqlcommand-dispose-required-if-associated-sqlconnection-will-be-disposed) – Daniel Earwicker Mar 02 '12 at 18:11

5 Answers5

15

It's generally simplest to follow the rule, "If the type implements IDisposable then use a using construct." So I'd go with some form of option 1.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
9

You need to wrap them both, although you can make it look slightly neater if that's bothering you!

using (var conn = new SqlConnection(/* ... */))
using (var cmd = new SqlCommand(/* ... */))
{
    // ...
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
2

The first one is definitely better.

Even when there is a relation between Connection and Command that makes the outer one sufficient, you don't want to rely on that, or expect your readers to know.

And such relations are always never documented and might change in future releases.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Would you clarify `Even when there is a relation between Connection and Command`. Thanks – Mubarek Mar 02 '12 at 18:40
  • The Command needs the connection, when you close the Connection you never hold on to resources on the server. Although connection pooling might make it less clear. Also see TextReader and Stream. – H H Mar 02 '12 at 19:32
1

No it's not enough, as a rule of thumb, enclose in a using block every time you instantiate an IDisposable.

vc 74
  • 37,131
  • 7
  • 73
  • 89
1

It is better to use two using commands (although there are alternative syntaxes) when you have multiples. It's better for garbage collection to be explicit about when you want access to those resources.

Community
  • 1
  • 1
Rudu
  • 15,682
  • 4
  • 47
  • 63