Object initializer in C#

PHPz
Release: 2023-08-29 16:05:10
forward
701 people have browsed it

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"
}
Copy after login

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

empDetails.EmpName
Copy after login

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; }
}
Copy after login

Output

10
Tim
Finance
Copy after login

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

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!