Wayne Werner
Wayne Werner

Reputation: 51787

Using multiple values in a using statement in C#?

In Python you can do something like:

with open('filename') as f, something_else(f) as thing:
    do_thing(thing)

and it will do the open bit, then the something_else bit. When the block exits it will "dispose" it in reverse order.

Right now I've got some C# code like this:

using (var cmd = new DB2Command(...)){
    using (var rdr = cmd.ExecuteReader()){
        // Magic super-duper-top-secret-code-here
    }
}

Is there any way that I can combine cmd and rdr into one using statement?

Upvotes: 0

Views: 146

Answers (3)

Quinton Bernhardt
Quinton Bernhardt

Reputation: 4793

So i'll try something not using using...

    public void processDisposables<T1, T2>(T1 type1, T2 type2, Action<T1, T2> action)
        where T1: IDisposable
        where T2: IDisposable {

            try {
                action(type1, type2);
            } finally {
                type1.Dispose();
                type2.Dispose();
            }
    }

and it's usage:

    processDisposables(new MemoryStream(), new StringReader("Frank Borland is 112"), (m, s) => {
        m.Seek(0, SeekOrigin.End);
        // other stuff with IDisposables
    });

Upvotes: 0

Servy
Servy

Reputation: 203802

You can only do this if the two objects share the same type, and they aren't here.

Note that there's no need for you to use braces on the outer using, and the code looks cleaner without it:

using (var cmd = new DB2Command(...))
using (var rdr = cmd.ExecuteReader())
{
    // Magic super-duper-top-secret-code-here
}

If the objects are both of the same type you can do this:

using(FileStream stream1 = File.Open("", FileMode.Open)
    , stream2 = File.Open("", FileMode.Open))
{
}

Upvotes: 4

Steven
Steven

Reputation: 172606

You can do this:

using (var cmd = new DB2Command(...))
using (var rdr = cmd.ExecuteReader())
{
    // Magic super-duper-top-secret-code-here
}

That's the best it will get.

Upvotes: 2

Related Questions