Simple answer is… it is just like a regular collection except that it implements a couple of pretty interesting interfaces, INotifyCollectionChanged and INotifyPropertyChanged. Let's dive in.
Take a look below.


What is so special about the ObservableCollection then? When would you use it?
The reason why you would use it, is the magic word called DataBinding, which is a lifesaver, especially when you are using Silverlight/WPF applications.
To bind to any variable/class is easy. The framework takes care of updating the value in the UI through an interface called INotifyPropertyChanged. As easy implementation can be found here. INotifyCollectionChanged interface implementation takes care of notifying the UI elements about items that are removed, updated, or inserted in the ObservableCollection.
Let's say you have a Country class as shown below.
public class Country
{
public Country(string name, string capital, string currency)
{
Name = name;
Capital = capital;
}
public Country()
{
// TODO: Complete member initialization
}
public string Name { get; set; }
public string Capital { get; set; }
}
If you want to create a List<Country> you can definitely do that! The issue would arise when you want to do data binding of the UI elements with this list. To avoid the extra hassle and code (implementing INotifyPropertyChanged and INotifyCollectionChanged interfaces yourself), you would use ObservableCollection<T> as follows.
public class AllCountryList : ObservableCollection<Country>
{
private static AllCountryList list = new AllCountryList();
static AllCountryList()
{
AddCountries();
}
private static void AddCountries()
{
list.Add(new Country { Name = "India", Capital = "New Delhi" });
list.Add(new Country { Name = "Pakistan", Capital = "Islamabad" });
list.Add(new Country { Name = "Sri Lanka", Capital = "Colombo" });
}
public static AllCountryList GetList()
{
return list;
}
}
The class is neat and is totally bindable. Assuming that CountryList is a list, you just need to do the following.
this.CountryList.ItemsSource = AllCountryList.GetList();
Create your UI appropriately (read more for help and an example), and it would be fully aware of the changes going on in the ObservableCollection!
Hope this helps.
Until next time,
Rahul
Quote of the day:
A large income is the best recipe for happiness I ever heard of. - Jane Austen