c z
c z

Reputation: 9027

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:

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

Upvotes: 0

Views: 1218

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460238

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...");
}

Upvotes: 3

Related Questions