-1

I m beginner in learning C#. i Saw some code but i have no idea how it works. Is there anyway to Change/Give values to the Property of an object at initialization.

For Example: i am declaring a Button and want to Change the Button.Name Directly

Button sender = new Button();

But i saw code something like:

Button sender = new Button({Name = "button_name"});

I am Trying to Shorten the Code From

Button btn = new Button();
btn.Name = "Mybutton";

to this:

Button btn = new Button({Name = "MyButton";});

But i Get syntax Error Here.

Sayed Muhammad Idrees
  • 1,245
  • 15
  • 25

1 Answers1

1

The issue with your code is that your syntax is not correct. The correct syntax for what you are attempting to do is:

Button btn = new Button()
{
    Name = "MyButton"
};

If you want to set more than one property during initialisation, use a comma to separate the property values:

Button btn = new Button()
{
    Name = "MyButton",
    Text = "Hello"
};

This is called an Object Initializer and was introduced in C# 3.0.

Martin
  • 16,093
  • 1
  • 29
  • 48