Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ObservableCollection<T>.Add work?

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?

like image 458
H.B. Avatar asked Feb 16 '11 22:02

H.B.


People also ask

How do I add items to ObservableCollection?

By default, you can use Add method to add a single item into ObservableCollection . To add a range of items, you can call the Add method multiple times using foreach statement.

How do you add items to ObservableCollection in xamarin forms?

Add(new Item() { ItemId = 1 }); // Also works for (int i = 1; i < 10; i++) { Items. Add(new Item() { ItemId = i }); } });

What is the use of an ObservableCollection?

An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions.

What is the difference between ObservableCollection and BindingList?

The true difference is rather straightforward: ObservableCollection<T> implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList<T> implements IBindingList .


2 Answers

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.

like image 144
Ani Avatar answered Sep 23 '22 05:09

Ani


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);
}
like image 44
Aaron McIver Avatar answered Sep 24 '22 05:09

Aaron McIver