Move Dispose call from caller to callee using yield
When a function returns a disposable object, it is responsibility of caller to dispose it (in the examples DisposableObject is an object that implements IDisposable interface).
DisposableObject DisposableObjectCreator()
{
return new DisposableObject();
}
void Caller()
{
using (var item = DisposableObjectCreator())
{
// ...
}
}
Sometime I feel comfortable to move Dispose responsibility from caller to callee using yield.
IEnumerable<DisposableObject> DisposableObjectCreator()
{
using (var obj = new DisposableObject())
{
yield return obj;
}
}
void Caller()
{
foreach (var item in DisposableObjectCreator())
{
// ...
}
}
Naturally, with this change the disposable object will be valid only into the defined loop, but I think that often this is an acceptable limitation.
It will be nice if will be possible to remove some bloating code (IEnumerable return type and for loop), writing something like this:
DisposableObject DisposableObjectCreator()
{
using (var obj = new DisposableObject())
{
yield return obj;
}
}
void Caller()
{
var item = DisposableObjectCreator();
// ...
}
And also, a way to notify programmer that he's using an object that won't be valid outside current block (a tag on the return type?).
The call of Dispose is only one of the possibly uses. It will be possible to add any code in a finally clause that envelopes the yield statement, that will run just after the caller code go outside the calling block.