Does the Clear method on the collection release provide event subscriptions?

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 # , .

+5
4

Clear() . ( , Clear() CollectionChanged Add() Remove() do.)

+4

CollectionChanged ObservableCollection, , , Clear, e.OldItems null Clear().

, @Michael, , , Clear, , :

public static class Extensions
{
    public static void ClearEx(this ObservableCollection<object> collection)
    {
        //custom clear logic...   
    }
}

Clear().

+1

Clear() .

, , , , Clear() .

, Remove() , Remove() , , , , .

0

Reflector:

protected override void ClearItems()
{
    this.CheckReentrancy();
    base.ClearItems();
    this.OnPropertyChanged("Count");
    this.OnPropertyChanged("Item[]");
    this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}

, , Collection Clear, , , , , , .

.

0

All Articles