23

Possible Duplicate:
using statement with multiple variables

I have several disposable object to manage. The CA2000 rule ask me to dispose all my object before exiting the scope. I don't like to use the .Dispose() method if I can use the using clause. In my specific method I should write many using in using:

using (Person person = new Person()) {
    using (Adress address = new Address()) { 
        // my code
    }
}

Is it possible to write this on another way like:

using (Person person = new Person(); Adress address = new Address())
Community
  • 1
  • 1
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200

4 Answers4

30

You can declare two or more objects in a using statement (separated by commas). The downside is that they have to be the same type.

Legal:

using (Person joe = new Person(), bob = new Person())

Illegal:

using (Person joe = new Person(), Address home = new Address())

The best you can do is nest the using statements.

using (Person joe = new Person())
using (Address home = new Address())
{
  // snip
}
Fabio
  • 3,020
  • 4
  • 39
  • 62
Jim Dagg
  • 2,044
  • 22
  • 29
20

The best you can do is:

using (Person person = new Person())
using (Address address = new Address())
{ 
    // my code
}
Z .
  • 12,657
  • 1
  • 31
  • 56
8

You could do

using (IDisposable iPerson = new Person(), iAddress = new Address())
{
    Person person = (Person)iPerson;
    Address address = (Address)iAddress;
    //  your code
}

but it's hardly an improvement.

Rawling
  • 49,248
  • 7
  • 89
  • 127
6

You can only use multiple objects in a single using statement if they are of the same type. You can still nest using statements without brackets.

using (Person person = new Person())
using (Address address = new Address())
{

}

Here is an example of a multiple object, same type using statement:

using (Person p1 = new Person(), p2 = new Person())
{

}
Caleb Keith
  • 816
  • 4
  • 10