0

I wish to define a one time label while adding it to controls, whats the correct syntax of doing so?

for example something like this:

this.Controls.Add(new Label
{ 
    .BorderStyle = label1.BorderStyle,
    .BackColor = label1.BackColor,
    .Text = "Breaks",
    .Font = label1.Font,
});
Deep Shah
  • 293
  • 5
  • 21
Tim
  • 165
  • 3
  • 9

3 Answers3

1

Just remove the . before the properties

this.Controls.Add(new Label
{ 
    BorderStyle = label1.BorderStyle,
    BackColor = label1.BackColor,
    Text = "Breaks",
    Font = label1.Font,
});

Object initializer in msdn.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

Object and Collection Initializers

this.Controls.Add(new Label
{ 
    BorderStyle = label1.BorderStyle,
    BackColor = label1.BackColor,
    Text = "Breaks",
    Font = label1.Font,
});

Make sure label1 is exists, so, don't call it before InitializeComponent()

mazharenko
  • 565
  • 5
  • 11
0

As you are using Object Initializer for the label control, you don't require the "." to set the values of the properties.

Example : Cat cat = new Cat { Age = 10, Name = "Fluffy" }; from MSDN

Anuraj
  • 18,859
  • 7
  • 53
  • 79