With relatively few exceptions (most of which can be described as the lowest level approaches to working with poorly developed code that cannot be modified), each instance of IDisposable must at any given time have exactly one clearly defined owner. In cases where the method returns something of the type that implements IDisposable , the contract for the method indicates whether the method of ownership is freed (in this case, the caller must ensure that the object is deleted - either by deleting the object on its own or abandoning ownership of someone to another), or the method simply returns a reference to an object belonging to someone else.
In correctly written code, the question of whether an object should be placed is rarely a court decision. The owner of the object must ensure its placement; no one else should dispose of it. Sometimes it may be necessary for a method to accept a parameter indicating whether the method should transfer ownership of IDisposable . For example, if the code wants to create a sound, pass it on to the method “start playing sound” and will never want to deal with this sound again, it may be most convenient for the code to play a sound that receives reception and delete the sound when it is done; however, if the code wants to be able to play sound several times, and will ensure that the sound object remains alive until it is needed, it would be more convenient if the sound code did not become owned. Using separate methods may be cleaner in some cases, but using a parameter can help encapsulation.
As a rule, when the code returns a list of objects that implement IDisposable , the purpose of the code is to identify objects without conveying any interest to them. In the absence of ownership, the code receiving such a list should not call Dispose on it.
source share