Implementing INotifyPropertyChanged without lambda expressions and “magic” strings

I think almost every .NET developer is familiar with INotifyPropertyChanged interface. Typical implementation of this interface looks more or less like that:

Thanks to lambda expressions we can get rid of so called “magic” strings when rising PorpertyChange event.

However, with .NET 4.5 we can even get rid of lambda expressions itself. Everything thanks to CallerMemberNameAttribute, which provides us information about caller of given method. Now we can rewrite NotifyPropertyBase class as follows

From this moment we can call OnPropertyChanged method without any arguments

and thanks to CallerMemberName attribute, argument propertyName will be filled with appropriate value.
callermembername
Source code for this post can be found here

Implementing INotifyPropertyChanged without lambda expressions and “magic” strings

One thought on “Implementing INotifyPropertyChanged without lambda expressions and “magic” strings

  1. It would be nice to mark property with attribute (something like [NotifyPropertyChanged]) instead of writing that repeatable code over and over again. I don't see any profits from [CallerMemberName] attribute. It only makes c# code more magical. Using Resharper 8 it's easy to transform autoproperty into property with backfield and with invocation of OnPropertyChanged . Microsoft modified the language only to facilitate writing in WPF framework (I suppose). I think it's wrong way. They should modified WPF instead of C#.

Comments are closed.