Anonymous Disposable – Adapter that makes any object IDisposable

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()) { /// .... }

3 Comments on “Anonymous Disposable – Adapter that makes any object IDisposable

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: