Determining if IDisposable should extend an interface or be implemented on a class implementing said interface

If you expect callers to only be able to interact with the interface, and never the implementation, then you want to have the interface extend IDisposable. If not, they’ll need to check if the value is IDisposable anyway to see if it needs to be disposed.

If the object responsible for disposing of the object knows of the concrete implementation, and it is only ever objects that are given references to it (but aren’t responsible for disposing of it) that use the interface, then consider the second option.

A good example of the first option is IEnumerator. Many IEnumerator objects don’t need to do anything when they’re disposed, but some do, and so the interface extends IDisposable because the object responsible for the creation/lifecycle of that object will (or should) never have knowledge of the underlying implementation.

An example of the second would be something like IComparer many objects that need to be compared are disposable, but the sections of code using an object through the interface aren’t responsible for it’s creation/lifecycle, so it needs no knowledge of whether or not that type is disposable.

Leave a Comment