Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can move the burden of disposing to the caller (return the disposable object and let the caller put it in a using statement).

In addition, if the caller itself is a long-lived object it can remember the object and implement dispose itself by delegating. Then the user of the long-lived object can manage it.



> You can move the burden of disposing to the caller (return the disposable object and let the caller put it in a using statement).

That doesn't help. Not if the function that wants to return the disposable object in the happy path also wants to destroy the disposable object in the error path.


You have to write a disposable wrapper to return. Return it in error case too.

    readonly record struct Result<TResult, TDisposable>(TResult? IfHappy, TDisposable? Disposable): IDisposable where TDisposable : IDisposable
    {
        public void Dispose() => Disposable?.Dispose();
    }


Usage at call site:

    using (var result = foo.GetSomethingIfLucky())
    {
        if (result.IfHappy is {} success)
        {
            // do something
        }
    }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: