INotifyPropertyChanged is an interface which is very important to do proper databinding and is heavily used in the MVVM pattern.

However, to implement it you have to raise the PropertyChanged event whenever a data-bound property changes value, and you have to pass the name of the property to it. This results in string based programming and this generally is not good for maintenance. Some people create a RaisePropertyChanged method in the base class and then invoke this method in each property setter. Again this is not ideal because you cannot always derive from this base class, especially if you already have a base class. In this post I want to show you an alternative way of implementing INotifyPropertyChanged that doesn’t require a base class (you simple implement the INotifyPropertyChanged on each class) with a nice, string-less way of raising the PropertyChanged event. For example, look at this class:

1:publicclass Customer : INotifyPropertyChanged

2: {

3:privatestring firstName;

4:

5:publicstring FirstName

6: {

7: get { return firstName; }

8: set

9: {

10:if (!object.Equals(value, firstName))

11: {

12: firstName = value;

13: PropertyChanged.Raise(this, o => o.FirstName);

14: }

15: }

16: }

17: }

As you can see, the PropertyChanged.Raise does all the work, and you pass in the sender and the property using a Lambda expression. Simple and no strings. To make things even simpler, I use a code snippet that implements the property directly for me:

This extension method has three arguments, the first two should be clear. The last is a LINQ expression.

When you invoke it the compiler converts this into a tree of objects, which represents the lambda expression o => o.FirstName, and passes it as an argument. This tree of objects is then traversed to find the MemberExpression which contains the name of the property. So the overhead is the creation and traversal of this small tree of objects. So it is a little less fast then passing a string, but the code is compile-time safe and supported by Visual Studio refactoring. This technique is generally known as static reflection.