Monthly Archives: August 2013

Annoyed with INotifyPropertyChanged?

Have you ever been annoyed with having to implement the cumbersome plumbing required for INotifyPropertyChanged ? Well, I have. So I tried to find a way to make authoring bindable objects better.

The typical example:

As you can see, it is quite verbose. The event and OnPropertyChanged() method need to be implemented for each class and it’s easy to get the implementation of OnPropertyChanged() wrong (typically introducing a race condition). Moreover, it’s 10 lines of code for each property. I hate that. The more you have to write, the bigger a surface for bugs to appear. A property should just boil down to   public string FirstName { get; set; } .

That won’t be possible of course. The default setters and getters just handle the assignment and loading of a compiler-generated backing field. So we somehow need to add the code for each property.

Enter Bindable objects

Similar to class NotificationObject, Bindable is here to help implementing INotifyPropertyChanged. The NotificationObject class only implements RaisePropertyChanged() but does not help with the implementation of the properties. Here is what you can do with Bindable:

Noticeably shorter, isn’t it ?

Behind the scene, Bindable uses a dictionary to store the property values. You probably have noticed that the property name is not given to Bindable.Get() or Bindable.Set(). Bindable leverages the compiler to provide the value automatically:

CallerMemberNameAttribute when applied on an optional parameter instructs the compiler to pass a string whose value is the name of the calling member. So when property FirstName calls Get<string>() , the compiler generates code for  Get<string>("FirstName") .

Here is the actual code for class Bindable:

Some aspects can be improved. For example, enabling subclasses to provide their own backing field. This is left as an exercise to the reader ;-)

I use this class a lot when implementing MVVM either in Wpf or Winforms.

What do you think ?

Edit: fixed code snippets as per Krumelur’s comments. Thanks Krumelur.