I was wondering if an ObservableCollection is guaranteed to maintain the order of elements inserted into it in C#. I looked at the MSDN site but could not find the answer.
The advantage of ObservableCollection over List is that it implements INotifyCollectionChanged. This interface raises an event whenever the collection is modified by insertion, removal, or replacement. A List does not implement this interface, so anything data bound to it will not be notified when it changes.
This is not true. Data binding works against anything that implements IEnumerable. You can data bind a list box directly to a List, if you want. The advantage of ObservableCollection over List is that it implements INotifyCollectionChanged. This interface raises an event whenever the collection is modified by insertion, removal, or replacement.
ObservableCollection ObservableCollection is a collection which allows subscribers to be notified when the contents of the collection are altered. This includes replacement of objects, deletion, addition, and movements.
While INotifyCollectionChanged and ObservableCollection are usable outside of a WPF UI, they are most commonly used for WPF data binding and were introduced for this task. We have already established that ObservedCollection which is the primary INotifyCollectionChanged implementation never sends more than one item.
ObservableCollection<T>
implements IList<T>
, which means that items are stored in the order you specify.
As a general rule, this is how the basic collection types in .NET work.
IEnumerable<T>
allows you to access the items one at a time, in an unspecified order.
ICollection<T>
allows you to add and remove items, and access the total size of the collection, in addition to IEnumerable<T>
capabilities.
IList<T>
allows you to access items by index and insert and remove items at arbitrary indices, in addition to ICollection<T>
capabilities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With