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.
...
image..."
Like Dan said, Nice....

1 comment:

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

    ReplyDelete

NOTE: Anonymous Commenting has been turned off for a while... The comment spammers are just killing me...

ALL comments are moderated. I will review every comment before it will appear on the blog.

Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...

I reserve, and will use, the right to not approve ANY comment for ANY reason. I will not usually, but if it's off topic, spam (or even close to spam-like), inflammatory, mean, etc, etc, well... then...

Please see my comment policy for more information if you are interested.

Thanks,
Greg

PS. I am proactively moderating comments. Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...