Using Lazy for implementing IDisposable pattern

Implementing the dispose pattern according to IDisposable can be very tedious. Why not simply use the new Lazy<T> to get rid of some boiler plate code? The trick is to define a Lazy<Action> with a function delegate which calls a release method. As long as you don’t access the value property of the lazy type the release method is not called. Lazy<T> offers the possibility to check whether the underlying value has been created or not (property IsValueCreated). Therefore we can use this to check whether we already disposed the underlying resources. Let’s see how this looks like in code:

    public class SomeDisposable : IDisposable  {
        private Lazy<Action> dispose;

        public SomeDisposable()  {
            this.dispose = new Lazy<Action>(() => this.Release);
        }

        public void Dispose() {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing) {
            if (disposing && !this.dispose.IsValueCreated) {
                this.dispose.Value();
            }
        }

        private void Release() {
            this.resource1.Dispose();
            this.resource2.Disconnect();
            this.resource2.Dispose();
        }
    }

Remarks: I left out the finalizer to not clutter up the code sample too much.

Happy lazy coding!

About the author

Daniel Marbach

Add comment

By Daniel Marbach

Recent Posts