Object Initializer in C#

Standard way of initializing an instance of the Employee class will be as follows (You can also use constructor).

using System;
namespace ConsoleApplication1
{
    public class Employee
    {
        public Employee()
        {
            this.ID = 0;
            this.Name = "N/A";            
            Address = "N/A";
        }       
        public int ID { get;set; }
        public string Name { get;set; }
        public string Address { get;set; }        
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.ID = 1;
            emp.Name ="Raj";
            emp.Address = "Pune";
            Console.ReadLine();
        }
    }
}


By taking advantage of Object Initializers of instance of the Employee class, you can modify your code as given below.
   

Employee emp = new Employee()
{
        ID = 1,
        Name ="Raj",
        Address = "Pune"
};


Object initializer enables you to assign values to any accessible fields or properties of class to initialize an object without having to explicitly invoke a constructor. By using "object initializers" you can easily assign data to properties in a type. The standard C# {  } brackets are used to create object initializers.

Suppose that there is another type Address for Employee in place of Address property, and then you can write the above code as:

Employee emp = new Employee()
{
     ID = 1,
     Name ="Raj",
     Address = "Pune",
     Address = new Address()
     {
            Street = "Diamond Street",
            City = "New York",
            Country = "USA"
      }
};