Partager via


Declare and set properties all at once

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.

Comments

  • Anonymous
    January 23, 2008
    IIRC, you shouldn't need to use the parens unless you're using a parameterized constructor.

  • Anonymous
    January 23, 2008
    Yes, you're right. I updated the post accordingly!