Initializers allow you to initialize values of properties within a class. If you have several properties for example, and you don’t want to define a constructor that will get all the values that will be supplied for those properties, then you can use an object initializer. For example, consider the code below.

using System;

namespace ObjectInitializerDemo
{
    public class Sample
    {
        public int Propertyone { get; set; }
        public string Propertytwo { get; set; }
        public bool Propertythree { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            Sample sampleClass = new Sample();
            sampleClass.Propertyone = 100;
            sampleClass.Propertytwo = "Sample";
            sampleClass.Propertythree = true;
        }
    }
}

Example 1 – Using an Object Initializer

As you can see, we need to assign new values to each of the properties one by one if we don’t define a proper constructor that will get all the three values in the initialization. By using object initializers, we can simplify our code.

public class Program
{
    public static void Main()
    {
        Sample sampleClass = new Sample    
        {                                  
            Property1 = 100,               
            Property2 = "Hello",           
            Property3 = true               
        };                                 
    }
}

You used curly braces instead of parentheses and inside it, you list the properties and the values to be assigned to them. You separate each property with a comma. When you use object initializers, the default parameterless constructor is called before each of the properties is assigned with a value. Since the default constructor is executed before the values are assigned to properties, you can specify default values for properties so that you don’t need to specify values for all the properties in the initializer. If you add a non-default constructor for your class, you must still provide a parameterless constructor to be able to use object initializers.

You can even nest object initializers. Let’s say our Sample class has a property of type Animal that has a Name and Age property.

Sample sampleClass = new Sample
{
    Property1 = 100,
    Property2 = "Hello",
    Property3 = true,
    Property4 = new Animal { Name = "Kitty", Age = 3 };
};

Another type of initializer are collection initializers. Collection initializers are similar to array initializers but they are used on generic collections.

List<Person> people = new List<Person>
{
     new Person("John"),
     new Person("Jenny"),
     new Person("Joe")
};

The code below shows that without using collection initializers, you need to  manually add the each items using the Add() method or create a constructor that  accepts the items for the collection.

List<Person> people = new List<Person>();

people.Add(new Person("John"));
people.Add(new Person("Jenny"));
people.Add(new Person("Joe"));