There are lots of examples of Arrays or Lists of IDisposable objects being returned from functions in .NET. For example, Process.GetProcesses()
.
I always thought it was the creator's burden to Dispose(). So what is the proper rule here?
The Dispose Method—Explicit Resource Cleanup Unlike Finalize, developers should call Dispose explicitly to free unmanaged resources. In fact, you should call the Dispose method explicitly on any object that implements it to free any unmanaged resources for which the object may be holding references.
The Dispose() method The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
NET calls an IDisposable object's Dispose() method once the code exits the block.
IDisposable is an interface that contains only a single method i.e. Dispose(), for releasing unmanaged resources. IDisposable is defined in the System namespace. It provides a mechanism for releasing unmanaged resources.
There is no general rule. It's going to depend on the situation, and how the method in question is designed, as to whether or not "you" are responsible for disposing of objects you have access to. This is where documentation is often important to help users of the type understand their responsibilities.
I always thought it was the creator's burden to
Dispose()
This cannot be strictly true. It is sometimes the case that a disposable object will out-live the lifetime of the block of code creating it. While it simplest when the creator can dispose of the object, sometimes it's simply impossible for them to be able to. When returning a disposable object from a method is one situation where it's often not be possible for the code creating the disposable object to clean it up, as it's lifetime needs to be smaller than the lifetime of the disposable object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With