Object Initializer in C#


Initialize an object of a class with object initialize.

Using it, you can assign values to the fields at the time of creating an object.

We created Employee object and assigned values using curly bracket at the same time.

Employee empDetails = new Employee() {
   EID = 10,
   EmpName = "Tim",
   EmpDept = "Finance"
}

Now access the values of the Employee class. For example, for name of the employee.

empDetails.EmpName

Let us see the complete code −

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      Employee empDetails = new Employee() {
         EID = 10,
         EmpName = "Tim",
         EmpDept = "Finance"
      };
      Console.WriteLine(empDetails.EID);
      Console.WriteLine(empDetails.EmpName);
      Console.WriteLine(empDetails.EmpDept);
   }
}

public class Employee {
   public int EID { get; set; }
   public string EmpName { get; set; }
   public string EmpDept { get; set; }
}

Output

10
Tim
Finance

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements