开发者

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 ni开发者_如何学JAVAce 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.


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 { ... };


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜