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() {

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

        private void Release() {

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