Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does The Clear Method On A Collection Release The Event Subscriptions?

Tags:

c#

collections

I have a collection

private ObservableCollection<Contact> _contacts;

In the constructor of my class I create it

_contacts = new ObservableCollection<Contact>();

I have methods to add and remove items from my collection. I want to track changes to the entities in my collection which implement the IPropertyChanged interface so I subscribe to their PropertyChanged event.

public void AddContact(Contact contact)
{
    ((INotifyPropertyChanged)contact).PropertyChanged += new PropertyChangedEventHandler(Contact_PropertyChanged);
    _contacts.Add(contact);
}

public void AddContact(int index, Contact contact)
{
    ((INotifyPropertyChanged)contact).PropertyChanged += new PropertyChangedEventHandler(Contact_PropertyChanged);
    _contacts.Insert(index, contact);
}

When I remove an entity from the collection, I unsubscribe from the PropertyChanged event. I am told this is to allow the entity to be garbage collected and not create memory issues.

public void RemoveContact(Contact contact)
{
    ((INotifyPropertyChanged)contact).PropertyChanged -= Contact_PropertyChanged;
    _contacts.Remove(contact);
}

So, I hope this is all good. Now, I need to clear the collection in one of my methods. My first thought would be to call _contacts.Clear(). Then I got to wondering if this releases those event subscriptions? Would I need to create my own clear method? Something like this:

public void ClearContacts()
{
    foreach(Contact contact in _contacts)
    {
        this.RemoveContact(contact);
    }
}

I am hoping one of the .NET C# experts here could clear this up for me or tell me what I am doing wrong.

like image 827
DaveB Avatar asked Mar 19 '10 21:03

DaveB


1 Answers

Clear() does not remove event handlers. (Note also, that calling Clear() does not trip a CollectionChanged event as Add() and Remove() do.)

like image 176
Scott J Avatar answered Sep 21 '22 15:09

Scott J