Search code examples
.netcollectionsidisposable

Standard Collection for IDisposable objects


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 ;-).


Solution

  • You're looking for CompositeDisposable.

        using System.Reactive.Disposables;
    
        ...
    
        CompositeDisposable xs = new CompositeDisposable(Disposable.Empty);
        xs.Add(Disposable.Empty);
        xs.Add(Disposable.Empty);
        xs.Dispose();