How does ObservableCollection<T>.Add work?

5.8k Views Asked by At

I was trying to implement a specialized collection that works like ObservableCollection to encapsulate some more mechanisms in it, to do that i also let my collection inherit from Collection and i also implement the same interfaces.

I just do not get though how one actually implements the whole collection-changed-logic, for example Collection<T>.Add is not being overridden (it is not even marked as virtual), so how does the ObservableCollection fire the CollectionChanged event if items were added using that method?

3

There are 3 best solutions below

10
On BEST ANSWER

To answer your specific question, Collection<T>.Add calls the InsertItem virtual method (after checking that the collection is not read-only). ObservableCollection<T> indeed overrides this method to do the insert and raise the relevant change notifications.

0
On

Remember, the key is not in overriding the base Collection methods, it's in the fact that you will be implementing the ICollection interface. And frankly, rather than inheriting from a Collection class, I would suggest instead creating an adapter class that takes a ICollection in the constructor and your methods will just delegate to the inner collection and raise the appropriate events.

1
On

It does so by calling InsertItem which is overridden and can be seen upon decompilation

protected override void InsertItem(int index, T item)
{
    this.CheckReentrancy();
    base.InsertItem(index, item);
    this.OnPropertyChanged("Count");
    this.OnPropertyChanged("Item[]");
    this.OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}