Skip to content
 

INotifyPropertyChanged, the Anders Hejlsberg Way

Back in September I was watching the Build session that Anders Hejlsberg was giving on the Future directions for C# and Visual Basic and something small but interesting stood out to me in the demo code he used.

We’re all pretty used to the standard boilerplate implementation of INotifyPropertyChanged that goes like this:

public event PropertyChangedEventHandler PropertyChanged;
 
private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}
 
private string companyNameValue = String.Empty;
public string CompanyName
{
    get { return this.companyNameValue; }
    set
    {
        if (value != this.companyNameValue)
        {
            this.companyNameValue = value;
            NotifyPropertyChanged("CompanyName");
        }
    }
}

The above code is taken directly from the MSDN article on “How to: Implement the INotifyPropertyChanged Interface“. What jumped out at me in Anders code, was that he was doing the check for equality in the helper method and not the property itself. The thought of doing this had crossed my mind before, but how could you create a method that could check for equality for any given type?

Enter the EqualityComparer<T>.Default property.

Using the Equals() method on EqualityComparer<T>.Default we can now create a generic method that compares the equality of two instances of any give type. This gives rise to the following INotifyPropertyChanged implementation that Anders used in his session:

public event PropertyChangedEventHandler PropertyChanged;
 
private void SetProperty<T>(ref T field, T value, string name)
{
    if (!EqualityComparer<T>.Default.Equals(field, value))
    {
        field = value;
        var handler = PropertyChanged;
        if (handler != null)
        {
          handler(this, new PropertyChangedEventArgs(name));
        }
    }
}
 
private int unitsInStock;
public int UnitsInStock
{
    get { return unitsInStock; }
    set 
    { 
        SetProperty(ref unitsInStock, value, "UnitsInStock");
    }
}

This not only reduces the property set implementation down to 1 line in most cases, but sets up a Pit of Success for properly implementing INotifyPropertyChanged in a class/subclass’s properties.

Nice.

(Bonus points for anyone who realized the current MSDN example code isn’t thread safe and contains a Race Condition.)

11 Comments

  1. Trev says:

    Dan, have you come across NotifyPropertyWeaver? I found it a few weeks ago http://code.google.com/p/notifypropertyweaver/

    • Dan Rigby says:

      @SimonCropp pointed it out to me on twitter yesterday. I’ve tended to shy away from code weaving approaches because they add additional complexity to the build process (not a a lot, but it’s an extra build step). I’m also not sure what the performance characteristics are for very large projects. Case in point, my current project is 2 million+ lines of code and each build takes roughly 7 minutes presently without code analysis. Code analysis builds take 20 minutes. I’m not opposed to code weaving approaches though. I may be swayed in the future.

  2. TimothyP says:

    Normally I use PostSharp to define a [NotifyPropertyChanged] attribute that I can attach to the properties.
    But I do like the solution you posted, one to keep in mind, thnx.

  3. See my Comment about this on the Channel 9 Show post. (At making this an extension method).
    http://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-Jan-13-2012

  4. [...] Dan Rigby brings in his blog a nice implementation of INotifyPropertyChanged – taken from Andres Hejlsberg: INotifyPropertyChanged, the Anders Hejlsberg Way [...]

  5. [...] INotifyPropertyChanged, the Anders Hejlsberg Way | Dan Rigby Like this:LikeBe the first to like this post. This entry was posted in Computers and Internet. Bookmark the permalink. ← What if You Didn’t Have to Commute? – TechTheHalls#fbid=-y_BDs1F-Uu [...]

  6. [...] The .NET 4.5 Way Posted by Dan Rigby on 1 March 2012, 8:27 pmPreviously I discussed a novel new way of implementing INotifyPropertyChanged based on code I saw during a Build [...]

  7. caddzooks says:

    I’ve used something similar to that for quite some time with one minor improvement, which is that my incarnation returns a bool indicating if the field value was actually changed, and is useful when other, dependent side-effects must be done in the setter if the property value has actually changed. I also have a version that stores the original field value in a dictionary keyed to the property’s name, for transactional purposes.

    • Dan Rigby says:

      I really like that idea of returning a bool. I was thinking the current approach had some disadvantages if you had some more complicated logic required in the setter, but the bool return value mitigates many of them. Thanks for sharing that.

Leave a Reply

(required)


− 5 = two