Declare and set properties all at once

Declare and set properties all at once

  • Comments 2

I used to use this technique in ActionScript, and I really like to use it C#:

TextBox textBox = new TextBox() { Text = "Hello!", Enabled = false };

TextBox
textBox = new TextBox { Text = "Hello!", Enabled = false }; // Thanks, kfarmer

Point
point = new Point(size) { X = 5 };

The only constructor that the TextBox class has is parameterless, but you can declare it and set its properties as shown in the examples. As kfarmer noted in his comment below, the parentheses are optional in case of a parameterless constructor.

Leave a Comment
  • Please add 8 and 4 and type the answer here:
  • Post
  • IIRC, you shouldn't need to use the parens unless you're using a parameterized constructor.

  • Yes, you're right. I updated the post accordingly!

Page 1 of 1 (2 items)