views:

158

answers:

3

I've got a bunch of IDisposable objects in a lookup table (plain old Dictionary<>, right now), but to simplify the code and avoid error's I'm looking for a collection class which "owns" the items it holds, and to avoid reinventing the wheel - does such a class already exist?

The specification should be that: - The collection must be disposable, and when it is disposed all contained items should be disposed too. - Whenever an item is removed, it is Dispose()-d first. - ideally, the collection would be generic with the type constraint enforcing the IDisposable-ness of the contained type.

I sorta doubt such a class exists, but I've been pleasantly surprised by the existence of ReadOnlyCollection and ObservableCollection before...

Essentially, I'd like the equivalent of the C++ STL containers but then for the CLR ;-).

A: 

I see what you're asking but how hard is it to make your own remove method that disposes the element before you remove it?

Sharath
Not hard at all - but it'd be cleaner to avoid it if possible.And, it's not just Remove, right - any method which may overwrite an element is implicitly replacing an existing element, which would need to be Dispose()'d too. If your collection implements a few standard interfaces, there can be quite a few variants of these remove/setter functions, leading to code bloat.
Eamon Nerbonne
+1  A: 

From what I know, there is only exits such collection for IComponents - Container implements IContainer. For generic IDisposable I think you have no other options but "reinvent the wheel".

arbiter
Thanks, I'll look into it (though it looks a little heavy weight - the API has a bunch of stuff I wouldn't be using - that might not matter)!
Eamon Nerbonne
Container and System.ComponentModel seem overly complex and insufficiently flexible for general use. In short, I'm accepting your answer that I have no other options but to "reinvent the wheel".
Eamon Nerbonne
+1  A: 

Remember that your collection might not be the only one containing the disposable objects ... What if another object (external to the collection) is referencing one of those? If you dispose it when the collection is disposed, then what would happen to the object?

If these objects implement IDisposable for some unmanaged resources cleaning then make sure they implement finalization as well and dispose of unmanaged resources there.

bruno conde
I currently fully control both the objects and the collection - so this is a hypothetical situation. In any case; that's just the way things work with IDisposables, right? I mean, *somebody* has to own (i.e. eventually Dispose) them, and in this case the owner happens to own a variable number of IDisposables, so a collection would be simplest.
Eamon Nerbonne