Thursday, September 17, 2009

Nested (inner) object initializers

Object initializers are probably most usable feature from C# 3 in my daily work. It was adopted by me since the beginning but only today I found that its support nesting, look:

var edit = new TextEdit();
edit.Name = "passwordEdit";
edit.Properties.PasswordChar = '*';

It's simple but real code, without initializers, how we can improve it? Before today's knowledge only like this:

var edit = new TextEdit{
   Name = "passwordEdit"
}
edit.Properties.PasswordChar = '*';

Because we can't write:

var edit = new TextEdit{
   Name = "passwordEdit",
   Properties.PasswordChar = '*'
}

And now, proper syntax:

var edit = new TextEdit{
   Name = "passwordEdit",
   Properties = {
                        PasswordChar = '*'
                }
}

Awesome. I hope some day we can attach event handlers with object initializers like Miguel de Icaza proposed.

No comments:

Post a Comment