If a class implements IDisposable
, that will generally impart to any code which creates instances of that class a responsibility to ensure that Dispose
gets called on that instance before it is abandoned; it may fulfill this responsibility either by calling Dispose
on the object itself when it is no longer needed, or by making sure that some other object that receives a reference accepts "ownership" and responsibility for it. In the majority of cases, when code is written correctly, each IDisposable
object upon which Dispose
has not yet been called, will at every point in time, have exactly one other entity (object or execution scope) which "owns" it. During the lifetime of the IDisposable
object, ownership may get passed among different entities, but when one object receives ownership the former object should relinquish it.
In many cases, objects will be used in such a fashion that tracking ownership is not difficult. Generally, any object whose state is ever going to be modified should have exactly one owner and that owner will know when the object is no longer needed. Additionally, because modification of the owned object's state would constitute modification of the owner's state, the owner itself should have a single owner. In such cases, requiring the owner to call Dispose
will not pose any difficulty (the owner's owner should call Dispose
on it). There is, however, a 'gotcha' with this principle: it's possible for an object to create an instance of a mutable class but never mutate it nor allow anyone else to do so. If the mutable class in question simply holds values and does not implement IDisposable
, objects which hold references to the things that will never actually mutate need not concern themselves with ownership. This can allow some major simplifications, since it will be possible for many objects to hold references to the non-changing object and not have to worry about which of them will use it last. If, however, the mutable class in question implements IDisposable
, such simplifications are no longer possible.