C# Object Initializer

Normally you use a constructor allows you to specify startup values when creating an object.

On the other hand properties allow you to set or get the underlying data of an object in a safe manner.

However, it’s not easy to create a single constructor that sets the underlying state data of an object. Even if it could be easy it doesn’t look tidy doing it that way.

C# provides us a cleaner syntax that streamlines this process of getting our object up and running. This syntax is the Object Initializer Syntax.

With this it’s possible to create an object and set a slew of properties to the object to it.

How does Object Initializer look like?

An object initializer comprises a comma-delimmited list of values enclosed by double curly braces({}) tokens.

Every member in the initialization syntax will map to the name of a public field or public property of the given object.

Advantages of Object Initializer

No. Advantage
1. It’s much tidy and cleaner.
2. It’s much more concise and allows us write less lines of code.

Examples

Say I want to create a Windows Forms with a slew of propeties:

Form myForm = new Form()
{
   Text = "Object Initializer Example",
   ClientSize = new Size(560, 430),
};            

In the above we have set the Text and ClientSize public properties via the Object initializer syntax.

Or a combobox with properties in one line :

comboBox = new ComboBox { Location = new Point(164, 176) ,DropDownStyle = ComboBoxStyle.DropDownList};

In this one we have set the Location and DropDownStyle public properties of our ComboBox via the Object initializer syntax.

Share



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )