Observable Collections ^2

An observable collection is an enhanced variant of a plain collection that notifies interested parties of any changes, such as items being added or removed. This is useful, amongst other things, if you want to keep a look-up table in sync or immediately reflect changes to a collection in the user interface. .NET provides support for such collections through its System.Collections.ObjectModel.ObservableCollection<T> class, which implements the INotifyCollectionChanged interface:

UML diagram of an ObservableCollection in .NET

Confusingly, this class, named like a collection, actually is a list. It’s not as big a problem as it was for the read-only collections because the observable collections don’t wrap an existing collection, but the inconsistent naming still irks me. The INotifyCollectionChanged interface also is not type-safe, requiring a downcast in the event subscribers.

So I rolled out my own set of observable collections complete with a type-safe interface:

ObservableList<T> and ObservableCollection<T>

The ObservableList<T> is largely equal to .NET’s own ObservableCollection<T>, but implements my IObservableCollection<T> interface in addition to the standard INotifyCollectionChanged interface. As explained above, my own ObservableCollection<T> actually is a collection and doesn’t support random access.

UML diagram of an my own observable collections

ObservableDictionary<K, T> and ObservableSet<K>

There have been moments when an ObservableDictionary<K, T> would have been a great thing to have. So I eventually added such a class to my extended collections as well:

UML diagram of an my own observable dictionary

Nothing spectacular, as all these really do is send change notifications with a KeyValuePair<K, T> or just the key K respectively, but I’m glad to have them in my toolbox in the few cases where I actually need them.


Nuclex.ObservableCollections.Demo.7z (13 KiB)

(Contains the source code of all observable collection classes with an example demonstrating their usage)

One thought to “Observable Collections ^2”

Leave a Reply

Your email address will not be published. Required fields are marked *

Please copy the string tVa4H1 to the field below:

This site uses Akismet to reduce spam. Learn how your comment data is processed.