Search code examples
c#.netdisposeidisposabletry-finally

Object that calls a method on Dispose


Is there a .NET class which calls a method when it gets disposed, sometimes instead of:

try
{
    ...
}
finally
{
    MyCleanupMethod()
}

I'd like to:

using(new OnDisposed(MyCleanupMethod))
{
    ...
}

Before I get berated, for three reasons:

  • For long try blocks it allows the reader to see what needs to be cleaned up at the start
  • try has an implication that its catching an error (which it's not)
  • To keep the disposal code private (if the IDisposable object is returned from a class)

Is this valid practice? If so, is a .NET class which does this?


Solution

  • You could add a constructor that takes the action:

    public class OnDisposed : IDisposable
    {
        private readonly Action _disposeAction;
        public OnDisposed(Action disposeAction)
        {
            _disposeAction = disposeAction;
        }
    
        public void Dispose()
        {
            // ...
            if(_disposeAction != null)
                _disposeAction();
        }
    }
    

    For example:

    using (new OnDisposed(() => Console.WriteLine("Dispose Called")))
    {
        Console.WriteLine("In using...");
    }