Object Initializer in C# with Example

Object Initializer in C# with Example
Object Initializer in C# with Example

We have seen how properties work in C#.  To assign values to properties, we create an instance of the class and assign them one by one in every new line.  To simplify this process, we make use of Object Initializer.  Object Initializer was introduced in C# 3.0 and it will definitely save your a lot of time while coding.  Using Object Initializer, instead of assigning properties in every new line, you can assign them directly while creating an instance of your class.  An example of Object Initializer in C# is given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{
    //using class
    class Employee
    {

        //Auto-Implemented property
        public string Name { get; set; }
        public int ID { get; set; }      
        

        public void Print()
        {
            Console.WriteLine("Employee Name: {0}", Name);
            Console.WriteLine("Employee ID: {0}", ID);
        }

    }


    class Program
    {
        static void Main(string[] args)
        {

            //Using Object Initializer
            Employee emp = new Employee() { ID = 20, Name = "Albert" };
            emp.Print();   
        }

    }
}

 Output:

Employee Name: Albert
Employee ID: 20
Press any key to continue . . .