views:

59

answers:

4

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.

+2  A: 

.Net 3.5 enhancement of Object Initializers, it is just a shorthand mechanism.

Andrew
Strictly speaking, it is a C# 3.0 thing, not a .NET 3.5 thing - you can use this when targetting .NET 2.0 from a C# 3.0 compiler.
Marc Gravell
+5  A: 

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 { ... };
Marc Gravell
ah! Thanks! And I figured out the last problem, which was that I forgot that thickness is not a double, but a Thickness object. :) So everything is great now, thank you. And if I run into a problem the next time, I'll know to search for "object initializer"!
Dave
+1 for a good answer + limitations noted.
Chris Ballance
thanks for editing and updating your answer, Marc. I also found the issue with event subscription. But it is pretty darn nice still. :)
Dave
A: 

It's called an object initializer and it doesn't have any disadvantages.

Maximilian Mayerl
It does have some limitations, though (see my (updated) answer)
Marc Gravell
+2  A: 

Object Initializer

It does the same thing under the hood. Second option uses a single line rather than two, which is nice & concise. .NET >= 3.5 only.

Chris Ballance