Undisposed instances
If all instances of a class are properly disposed, the number of undisposed instances will be zero. As mentioned previously, it is preferable to make sure that all instances are properly disposed, but there is a set of disposable classes whose instances do not need to be disposed. These classes do not contain native resources, do not reference other disposable classes, do not need to be cleaned up, and do not have a finalizer. Usually these classes should not be disposable in the first place, but they might be derived from a base class that expects its derived classes to possibly contain native resources, or they might be used as base classes for other classes that may contain native resources.
An example of a disposable class that does not need to be disposed is the System.IO.MemoryStream
class, since it only references managed memory and has no finalizer. It is derived from System.IO.Stream
, an abstract class that can expect classes derived from it to contain native resources, e.g., file handles and network sockets. It therefore implements IDisposable
, even though not all derived classes will contain native resources, e.g., System.IO.MemoryStream
.
Even though there are disposable classes whose instances do not need to be disposed, it is recommended that all instances of all disposable classes always be disposed, unless you are certain that an instance does not need to be disposed.
Note
There are several disposable classes in the framework whose instances are not always disposed. You should not try to dispose these instances yourself, even if you have a reference to the instance. For example, instances of PaintEventArgs
are not always disposed, and it would be possible to dispose them at the end of the OnPaint
method, but that might have undesired consequences. You must only dispose an instance if you clearly know that you are the one responsible for disposing it, and that it is not being used elsewhere.