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?
Asked
Active
Viewed 287 times
1
-
1No, `Dispose()` is not called. – Progman Aug 02 '20 at 08:52
-
1Why would you expect that removing an item from a list would destroy the item? – Caius Jard Aug 02 '20 at 08:53
-
Does this answer your question? [How to handle add to list event?](https://stackoverflow.com/questions/1299920/how-to-handle-add-to-list-event) – Progman Aug 02 '20 at 08:53
-
1*is there some way to call it when objects are being removed?* - wrap the list or subclass Collection
to create a collection for your objects, that ensures Dispose is called on the item removed. See also: https://stackoverflow.com/questions/5376203/inheriting-from-listt – Caius Jard Aug 02 '20 at 08:59 -
@CaiusJard I have modified his question, please answer – Vivek Nuna Aug 02 '20 at 08:59
-
3@viveknuna I rolled back your edit; it adds words that the original author did not write. Please acquaint yourself with what is, and is not acceptable when editing a question – Caius Jard Aug 02 '20 at 09:00
-
@CaiusJard no problem, but can you please answer my question – Vivek Nuna Aug 02 '20 at 09:01
1 Answers
5
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();
}
}