BlackWaspTM
.NET Framework
.NET 1.1+

Implementing IDisposable

by Richard Carr, published at http://www.blackwasp.co.uk/IDisposable.aspx

Classes that use unmanaged resources, or that hold references to managed objects that themselves use unmanaged resources, should always implement the IDisposable interface. The correct use of this interface ensures the efficient release of resources.

What is IDisposable?

IDisposable is an interface defined in the System namespace. The interface defines a single method, named "Dispose", that is used to perform clean-up activities for an object when it is no longer required. The method may be called manually, when an object's work is finished, or automatically during garbage collection.

The IDisposable interface was designed to provide a standard way to release unmanaged resources. These are resources that the garbage collector does not manage on our behalf and is unable to clean up automatically. They include items such as streams, files, database connections and handles. If the memory and system resources that they use are not properly released, your software may suffer from memory leaks or problems due to locked resources.

If you develop a class that owns unmanaged resources, you would normally include a finalizer or destructor that releases those resources when objects go out of scope. However, as the actual execution time of the finalizer is not predictable, the resources can stay allocated for longer than is desirable. By implementing the IDisposable interface, you allow the disposal of such resources to be requested immediately, rather than waiting for the garbage collector.

If you create a class that does not use unmanaged resources then you should not implement IDisposable. However, you should consider whether class-scoped variables within your code are of types that themselves implement the interface. For example, if you hold a Stream object at this scope, you should implement IDisposable and call the Dispose method on this object when releasing resources. This ensures that the unmanaged file handle controlled by the Stream object is released as early as possible.

NB: Sometimes the objects that a class utilises are shared. You should take care when disposing these as they become unusable once released. If the object is still required elsewhere, exceptions will occur.

Implementing IDisposable

There are several options to consider when implementing the IDisposable interface. In this article we will start with the basic pattern that should be used. We will then modify this pattern to show how to implement the interface when a finalizer is required and in an inheritance relationship. You can download the example classes using the link at the top of this page.

6 August 2008