Monday, January 09, 2012

Taking INotifyPropertyChanged Properties from 4/5 lines to 1 (Or "Taking the Anders Hejlsberg Way to INotifyPropertyChanged")

Dan Rigby - 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:
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:
Which reduces the property set implementation down to 1 line from 4-5 (depending on brace layout) for most cases.
Like Dan said, Nice....

1 comment:

Annie Calvert said...

It is a great article to get know more about how to increase .net performance using I NOTIFY PROPERTY CHANGE.Thanks for sharing.