1

is it same for the following two code snippets

Snippet 1:

using()
using()
{
   blah blah blah
}

Snippet 2:

using ()
{
  using ()
  {
    blah blah blah
  }
}
Mia Clarke
  • 8,134
  • 3
  • 49
  • 62
user496949
  • 83,087
  • 147
  • 309
  • 426
  • possible duplicate of [Nested using statements in C#](http://stackoverflow.com/questions/1329739/nested-using-statements-in-c) – Richard Nov 11 '10 at 11:15

3 Answers3

6

They are functionally the same.

See this SO question and answers for some more detail and options for using statements.

using(TypeX x = new TypeX())
using(TypeY y = new TypeY())
{
   blah blah blah
}

Is exactly the same as:

using(TypeX x = new TypeX())
{
  using(TypeY y = new TypeY())
  {
   blah blah blah
  }
}

Also, if your are initializing two variables of the same type, you can do the following:

using(TypeY y1 = new TypeY(), y2 = new TypeY())
{
   blah blah blah
}
Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
4

Yes, exactly the same.

LukeH
  • 263,068
  • 57
  • 365
  • 409
1

Yes, it is same as long as you don't put anything else in between first and second using or between the closing brace of first and second using.

For example, if you change this code to something like:

using ()
{
    using ()
    {
        blah blah blah
    }
    blah blah blah
}

OR

using ()
{
    blah blah blah
    using ()
    {
        blah blah blah
    }
}

OR a combination of both of the above, then it would be different.

Aamir
  • 14,882
  • 6
  • 45
  • 69