How to dispose a list of disposable objects?

Who creates the objects inside the list? i.e. who is responsible for their life-cycle? If MyDisposable creates them, then it is its responsibility to dispose of them. If someone else creates them, disposing of them can leave them with a reference to a useless object.


Yes, iterate through the list and dispose each item.

Also you can write an extension method:

public static void Dispose(this IEnumerable<IDisposable> collection)
{
    foreach (IDisposable item in collection)
    {
        if (item != null)
        {
            try
            {
                item.Dispose();
            }
            catch (Exception)
            {
                // log exception and continue
            }
        }
    }
}

and call it for your list

coll.Dispose()

Disposable collection, a collection that implements IDisposable:

public sealed class DisposableCollection<T> : Collection<T>, IDisposable
    where T : IDisposable
{
    public DisposableCollection(IList<T> items)
        : base(items)
    {
    }

    public void Dispose()
    {
        foreach (var item in this)
        {
            try
            {
                item.Dispose();
            }
            catch
            {
                // swallow
            }
        }
    }
}

Usage:

using (var coll = new DisposableCollection(items))
{
     // use
}
// it has been disposed