Wednesday, August 27, 2008

Automatically implemented properties and WPF

This blog hasn’t lived much recently – I’ll try to post a little more, but no promises (since noone reads it anyway).

I’ve been looking into Windows Presentation Foundation lately, and it is very fascinating; It opens up a lot of doors for new UI possibilities, but also quite a few new challenges. If you want to display your object model in the “WPF way”, one of the things you have to do is implement INotifyPropertyChanged. This allows WPF to pick up on object changes and update the user interface accordingly.

One of the very helpful new features in C# 3 (i.e. the language, which confusingly was released with .Net 3.5) is automatically implemented properties. Basically these guys allow you to implement trivial properties on objects without a lot of code, backing fields etc. A one-line property makes code more readable, and you have less possibility of failure in a no-code property than one that contains some code.

These two things put together, however, are currently not compatible by default. If you have an automatically implemented property, it will not notify WPF of changes to its’ value. There are of course ways of doing this using reflection and attributes and such, but wouldn’t it be really cool if the C# compiler knew of INotifyPropertyChanged and actually triggered the PropertyChanged event for you automatically on these autoprops?

I certainly think so, but I can see why some people would disagree.

No matter what, I think it would be really useful.

1 comment:

Anonymous said...

I totally agree. There are several of these interfaces that has been introduced that really annoys developers having to implement all the boilerplate code over and over again.

There are several ways to tackle this issue.

Attributes:
Make all creation of all objects go through an object factory and make use of attributes to tell which properties should notify about their change. The factory would then inject the code for doing this. The drawback is that you need the properties to be virtual or abstract, as the factory needs to create a new dynamic type.


Language magic:
Exploit the wonderful world of C# 3.0 and use lambdas and the LINQ expression trees to make the compiler work with us. :) Read more: http://www.ingebrigtsen.info/post/2008/12/11/INotifyPropertyChanged-revisited.aspx


Compiler extensibility:
My all time favorite would be to have the ability to extend C# with new keywords or macros that would expand during compiletime. Then one could introduce a "keyword" called notify that one would prefix a property with it and the compiler extension would fill in the blanks. Read more about it here: http://www.ingebrigtsen.info/post/2008/11/03/Compiler-extensions-is-just-another-framework.aspx