Yurii Urshanskyi
Yurii Urshanskyi

Reputation: 45

Does the method List<T>.Remove() call the method Dispose() from the removing object?

I have several objects in collection List. I need to know whether the method Dispose() is called when objects are removing from collection? If not, whether is there some way to call it when objects are being removed?

Upvotes: 1

Views: 592

Answers (1)

Orkad
Orkad

Reputation: 670

You will have to create your own collection class who manage disposing. Actualy list & collection has nothing to do with object lifetime.

public class AutoDisposeList<T> : IList<T> where T : IDisposable
{
    public void Add(T item)
    {
         base.Add(item);
    }
    
    public void RemoveAndDispose(T item)
    {
        base.Remove(item);
        item.Dispose();
    }
    
}

Upvotes: 5

Related Questions