September 9, 2012

A learning from ObservableCollection

Yesterday, I was working on my hobby project (which is going to be released any day soon), I faced a weird issue. I wanted to create a list of ScheduledNotification (reminders/alerts) and show them to user. Obvious choice for the list was ObservableCollection, to automate the UI updates. So, I followed these steps to create that collection and bind it to UI. First, let’s understand what is going here and then we’ll solve the issue.

Step 01: Creating ObservableCollection and binding it to ListBox:

image

Step 02: On a click of a button, create random reminders, get those collections in list and add them to ObservableCollection.

image

Step 03: Removing the objects from ObservableCollection

Usually, to remove the objects, any developer will use Remove() method on this collection like:

image

However, this method not only failed to remove this object, but when I tried searching for “rem2” in the collection, it returned false, –1. Stating that object doesn’t exists.

image

So, what is the issue. To solve this mystery, we need to go back and revisit the OOP concept i.e. two classes are same only if they’re pointing (or referring) to same location. Here, ObservabaleCollection stored a different location and returned me false.

To, solve this issue, a different kind of logic needs to be applied and i.e.:

image

This is the perfect example, where we need to always remember the fundamentals of OOP.

I hope, it helps.

Namaste

Mayur Tendulkar | www.mayurtendulkar.com