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 -
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; } }
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!