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?
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:If the objects are both of the same type you can do this: