There are quite a few API’s out there that have for example a ‘Close()’ method but don’t implement dispose. Or if you want to put something under ‘using’ statement and preform a certain action when the ‘using’ finishes.
Here is a very simple example that alloys you to turn anything into IDisposable.
public static class Diposable { public static IDisposable Create(Action action) { return new AnonymousDisposable(action); } private struct AnonymousDisposable : IDisposable { private readonly Action _dispose; public AnonymousDisposable(Action dispose) { _dispose = dispose; } public void Dispose() { if (_dispose != null) { _dispose(); } } } }
Here is an example :
var resource = ...; using(Disposable.Create(()=> resource.Close()) { /// .... }