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.