I found out two interesting things about the ExpandoObject class introduced in C# 4 this bank holiday weekend:
1. you can specify custom events on them
2. it implements the INotifyPropertyChanged interface
Here are some quick demos to show you how to use these features:
To add a custom event is the same as adding a new property:
Generic event handlers will work too:
Because we’ve initialize the events with null, we’ll get a runtime exception if we try to invoke the event before it’s subscribed to (which is the same as normal custom events). So instead, we can use the same pattern I mentioned here, and initialize the custom events with an event handler that does nothing:
You should be familiar with the INotifyPropertyChanged interface already as it’s pretty damn important when it comes to data-binding in UI technologies such as WPF and Silverlight. So having a dynamic object you can easily bind with can help save you plenty of time and effort as anyone who’s ever had to write code to implement the interface will tell you!
As you can see from the code snippet above, the PropertyChanged event is fired whenever a property is added, removed or changed.
It’s also worth noting that there is another dynamic class that was introduced alongside the ExpandoObject – the DynamicObject class, which offers you more granular control of what happens when someone tries to access/update a dynamically defined property or method.
Whilst the DynamicObject class doesn’t implement the INotifiyPropertyChanged interface itself,it is possible for you to extend it to implement the interface yourself, as described by this MSDN magazine article.