http://blogs.clariusconsulting.net/kzu

Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

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.

Adding this to the IL generated by the compiler for object initializers would make them immensely more useful. I’d be willing to replace many ctor overloads with properties if I had that hook, given the much more readable code that results from using object initializers.

 

Microsoft Connect site used to be the place where you suggested things. I did for this one, and Mads Torgersen, C# Language PM, liked the idea. But alas, they closed the bug as Won’t Fix back in 2008 (as it was way too late for C# 4.0/VS2008) and never reopened it. I cannot reopen it either now for consideration for C# 5.0. And it seems in the meantime, they changed their mind and now suggestions should go to a UserVoice site. Sigh.

So I basically cloned the suggestion in the new site. Please go vote to get support for ISupportInitialize on object initializers in C# 5.0!

Comments

1 Comment