CSharp - Object Initializers vs normal way

Introduction

We are going to use two different techniques in object creation.

Demo

using System;


class Person/*from  ww w  .  j ava  2 s  . c  o m*/
{
    public string Name;
    public int Id;
    public double Salary;
    //Parameterless constructor 
    public Person() { }
    //Constructor with one parameter 
    public Person(string name) { this.Name = name; }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("***Object initializers Example-1***");

        //Part-1:Instantiating without Object Initializers 

        //Using parameterless constructor 
        Person emp1 = new Person();
        emp1.Name = "A";
        emp1.Id = 1;
        emp1.Salary = 10000.23;
        //Using the constructor with one parameter 
        Person emp2 = new Person("Sumit");
        emp2.Id = 2;
        emp2.Salary = 20000.32;

        //Part-2:Instantiating with Object Initializers 

        //Using parameterless constructor 
        Person emp3 = new Person
        {
            Name = "Bob",
            Id = 3,
            Salary =
           15000.53
        };
        //Using the constructor with one parameter 
        Person emp4 = new Person("Robin") { Id = 4, Salary = 25000.35 };

        Console.WriteLine("Person Details:");
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp1.Name,
           emp1.Id, emp1.Salary);
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp2.Name,
           emp2.Id, emp2.Salary);
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp3.Name,
           emp3.Id, emp3.Salary);
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp4.Name,
           emp4.Id, emp4.Salary);
        Console.ReadKey();
    }
}

Result

Note

In Part-2 of this example, we used object initializers.

In the Part-1, we needed to code more lines to initialize the objects compared to the part 2.

In Part-2, a single line of code was sufficient to instantiate each of the objects.

object initializers simplify the instantiation process.

Related Topic