Hacker News new | ask | show | jobs
by neonsunset 844 days ago
defer is a poor man’s C# IDisposable (or even IAsyncDisposable)

    // The file handle will be freed at OS level when exiting current scope
    using var file = File.OpenHandle("somefile");
1 comments

defer is best compared to try/finally or unwind-protect and friends. You can defer any action, not just whatever the IDisposable happens to cleanup. It also gets access to the lexical scope for its deferred actions.

You could imitate that with IDisposable, but it would be overkill compared to just using finally (in C#).