New way of PropertyChanged notification in .NET4.5

Since the release of Win8 Comsumer Preview and VS11 Beta I am playing around with this new stuff. Altough there are lots of improvements I am unhappy with the fact that there is no “compiler as a service” – yet. So I will patiently wait for the next version…

Nevertheless, there are other cool features in the new version of my beloved .NET framework that’ll make my days. One of those is support of CallerInformation through optional parameters. Using the new CallerMemberNameAttribute in an extension method for the PropertyChanged event, we can dramatically simplify property change notification from a set accessor.

public static class NotifyPropertyChangedExtension
{
    public static void On(this PropertyChangedEventHandler self,
                          object sender,
                          [CallerMemberName]string propertyName = null)
    {
        if (self != null)
            self(sender, new PropertyChangedEventArgs(propertyName));
    }
}

You can use this from your properties as shown below:

public string CustomerName
{
    get { return _name; }
    set
    {
        if(_name != value)
        {
            _name = value;
            PropertyChanged.On(this);
        }
    }
}

I also think this reads very well. Since every setter will require the identical line of code, packing this into a code snippet is very easy as well.

Nevertheless, there are some restrictions to this approach:

  • It will only work when called from the affected property. When calling this from another place, you must provide the property name as the second parameter.
  • It will not work for Multi-PropertyChanged notification. I have an idea of how to solve this task with an additional lambda expression, but this is something for another post.

Have fun with this piece…

Leave a Reply

Your email address will not be published. Required fields are marked *