I have a collection
private ObservableCollection<Contact> _contacts;
In the constructor of my class, I create it
_contacts = new ObservableCollection<Contact>();
I have methods for adding and removing items from my collection. I want to track changes in the objects of my collection that 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 object from the collection, I unsubscribe from the PropertyChanged event. I was told that this allows the entity to collect garbage, rather than create memory problems.
public void RemoveContact(Contact contact)
{
((INotifyPropertyChanged)contact).PropertyChanged -= Contact_PropertyChanged;
_contacts.Remove(contact);
}
, , . . _contacts.Clear(). , ? ? - :
public void ClearContacts()
{
foreach(Contact contact in _contacts)
{
this.RemoveContact(contact);
}
}
, .NET # , .