Search code examples
wpfobjectelementinstantiationcreation

What is this method of element instantiation called?


Whenever I create a UIElement in code behind, I'd do something like this:

Button button = new Button();
button.Content = "Click Me!";

But then I saw this syntax somewhere, and wanted to know what it's called. I haven't ever seen it used in any of my .NET books:

Button button = new Button { Content="Click Me!" };

This is obviously nice because it's concise. So I guess my questions are:

  1. what's it called?
  2. are there any disadvantages to instantiating a UIElement in this manner?

I've also had trouble figuring out the right way to set properties like CornerRadius and StrokeThickness, and thought the answer to #1 might help me make more intelligent search queries.


Solution

  • 1: An "object initializer"

    2: Nope; it is very handy for code samples, in particular ;-p

    Things you can't do in an object initializer:

    • subscribe events
    • combine with collection initializers on the same collection instance (an initializer is either an object initializer (sets properties) or a collection initializer (adds items)

    You can get past these limitations by cheating:

    Button btn;
    Form form = new Form { Text = "Hi", Controls = { (btn = new Button()) }};
    btn.Click += delegate { ... };