Search code examples
c#.netvb.netidisposable

To Dispose() or Not To Dispose() elements in an array of IDisposable objects?


There are lots of examples of Arrays or Lists of IDisposable objects being returned from functions in .NET. For example, Process.GetProcesses().

  • If I call that method is it my responsibility to Dispose() of all the members of the array as I iterate through them?
  • Why should it be my responsibility since I never created the objects and the array that I was given is just pointers to the objects which were created outside of my code.

I always thought it was the creator's burden to Dispose(). So what is the proper rule here?


Solution

  • 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.