I have a class hierarchy, each member of which may create IDisposable
objects.
I added a List<IDisposable>
property to the base class in this hierarchy, to which I add any disposable objects on creation. The root Dispose
method iterates through this list and calls Dispose
for each item in its list and clears the list. In the application, I explicitly call the top object's Dispose
method, causing disposal to cascade through the hierarchy.
This works, but is there a better way? Am I unwittingly duplicating some functionality already present in the framework?
(Note - the objects in question have a lifetime that precludes just wrapping them in a using
block or disposing of them in the same methodwhere they are created.)
Edit
Just for clarification - I'm only keeping those objects around that need to be kept. Some are disposed of in the same method where they are created, but many are used in such a way that this isn't possible.