How to make object initializers more useful

Quite often, it's necessary to validate an object state when it's initialized. With constructor arguments, this is easy to do as it can be done at the end or beginning of the constructor code. With object initializers, it's nearly impossible, as there's no way to know programmatically when the object initialization is finished.

There's a built-in mechanism for this that is being used in WinForms and WPF: the ISupportInitialize interface. The initialization code generated by both toolkits checks to determine if the object implements the interface. If it does, it will call BeginInit() before invoking all property setters, and EndInit() at the end. This provides a nice hook for validating all properties and maybe interrelated ones....

Read full article

No Comments