0

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?

3 Answers 3

4

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)) { } 
Sign up to request clarification or add additional context in comments.

1 Comment

@Steven It's a widely used pattern.
2

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.

Comments

0

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 }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.