Reputation: 9027
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:
try
blocks it allows the reader to see what needs to be cleaned up at the starttry
has an implication that its catching an error (which it's not)private
(if the IDisposable
object is returned from a class)Is this valid practice? If so, is a .NET class which does this?
Upvotes: 0
Views: 1218
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