Daily Archives: October 24, 2010

Why to use ObservableCollection instead of List in Silverlight

List<T> represents a strongly typed list of objects that can be accessed by index. It provides methods to search, sort, and manipulate lists.

We use List<T> to assign DataSource to Controls in ASP.Net (eg. DataGrid, Dropdownlist etc). Once we assign List<T> to DataGrid it becomes stateless. DataGrid will be displaying data even if all the items of that collection have been removed. To reflect the changes in DataGrid user has to refresh the page. To solve this problem in Silverlight we have ObeservableCollection<T> collection. ObservableCollection is a generic dynamic data collection. It is capable to provide item added/deleted notifications to client with the help of “INotifyCollectionChanged” interface. INotifyCollectionChanged interface has an event “PropertyChanged”. It occurs when a property value is changed.

WCF service proxy class in Silverlight uses ObservableCollection<T> by default.

While adding the service reference to the Application we can change Collection type.

clip_image002

As you can see in below code that type of e.Result is ObservableCollection<T> because I have set collection type to ObservableCollection while adding reference. Type of e.Result gets changed automatically according to Collection Type.

clip_image004

Implemention of INotifyPropertyChanged interface

In below code Employee class implements INotifyPropertyChanged interface and whenever name property is changed we are calling onPropertyChanged method. Further it will raise PropertyChanged event and it will send notification to client.

clip_image005

Happy Coding :)

MSCoder