Over a million developers have joined DZone.

Code Snippets for the Dispose Pattern

·

I thougth I’d just share a couple of Visual Studio C# code snippets to implement disposable classes, based on the well known .NET dispose pattern.

You can download it from here or simply copy and past it from the listing below. Feel free to rename the shortcut to whatever you like :)

    public class $ClassName$: IDisposable
    {
        private bool _disposed = false;

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

        protected virtual void Dispose(bool disposing)
        {
          if (!_disposed)
          {
            if (disposing)
            {
              // Free other state (managed objects).
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.
            _disposed = true;
          }
        }

        // Use C# destructor syntax for finalization code.
        ~$ClassName$()
        {
          // Simply call Dispose(false).
          Dispose(false);
        }
    }
  public class $DerivedClassName$: $BaseClassName$
  {
      private bool _disposed = false;

      protected override void Dispose(bool disposing)
      {
          if (!_disposed)
          {
              if (disposing)
              {
                  // Release managed resources.
              }
              // Release unmanaged resources.
              // Set large fields to null.
              // Call Dispose on your base class.

              _disposed = true;
          }

          base.Dispose(disposing);
      }
      // The derived class does not have a Finalize method
      // or a Dispose method without parameters because it inherits
      // them from the base class.
  }
Topics:

Published at DZone with permission of Stefano Ricciardi, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}