Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

Dispose pattern (C#)

Pretty common pattern: if you are working on a class that utilize either unmanaged resources or managed disposable classes, you need to make your class disposable as well.

    class DisposePatternClass : IDisposable
    {
       /// <summary>
        /// Doesn't allow to dispose same instance twice
        /// </summary>
        private bool disposed = false;

       /// <summary>
        /// Privately cleaning up both managed and unmanaged resources
        /// </summary>
        /// <param name="disposing">True is DisposePatternClass.Dispose() was called; false if disposing by GC</param>
        private void CleanUp(bool disposing)
       {
           if (!this.disposed)
           {
               if (disposing)
               {
                   // Disponse Managed resources here
                }

               // Clean up Unmanaged resources here
            }

           disposed = true;
       }

       /// <summary>
        /// Manual Dispose
        /// </summary>
        public void Dispose()
       {
           CleanUp(true);
           GC.SuppressFinalize(this);
       }

       /// <summary>
        /// Destructor
        /// </summary>
        ~DisposePatternClass()
       {
           CleanUp(false);
       }
   }

Have fun!

Add comment