Just move the method call outside of the using
statement and then just use the disposable object:
var (disposable, number) = foo();
using (disposable)
{
// do some stuff using disposable and number
}
The reason your version didn’t work is simply because whatever the expression inside the parentheses of the using
results in needs to be disposable but the value tuple itself is not disposable. So you just need to split this up. Fortunately, the using
statement is not required to construct the object within that expression, you can just pass any existing object to it.
Actually I'd like to see the new ValueTuples implement the IDisposable
interface and call Dispose()
on all their disposable members. Could this be a worthwhile feature request for Microsoft?
By that logic, all collections would be have to do that. For example disposing a list should dispose all its members, disposing a dictionary should dispose all its values (and keys?!?!). And when you have a type just using a simple list, that object would also need to be disposable.
So basically, you would end up spreading that and end up with a lot of objects that are suddenly disposable although they don’t actually have any actual resources that require it.
Making objects disposable shouldn’t be done lightly. Usually, objects creating a disposable object become responsible for properly disposing the object later, they own the lifetime of the object. But for collections, this is very often not the case. Collections are usually just that: Collections to hold on to objects, but that does not say anything about whether or not they are owned by the collection—most of the times they are owned by the object that also created the collection, so that object should then at some point dispose the objects by simply looping through the collection.