Home  >  Article  >  Backend Development  >  Object initializer in C#

Object initializer in C#

PHPz
PHPzforward
2023-08-29 16:05:10730browse

C# 中的对象初始化器

Use object initialization to initialize the object of the class.

Using it, you can assign values ​​to fields when creating an object.

We create the Employee object and assign it using curly braces.

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

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

empDetails.EmpName

Let’s 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

The above is the detailed content of Object initializer in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete