Collection Initialization in C#


Initialize Collection like class objects using collection initializer syntax.

Firstly, set values for the Employee object −

var emp1 = new Employee() { EID = 001, EmpName = "Tim", EmpDept = "Finance"};
var emp2 = new Employee() { EID = 002, EmpName = "Tom", EmpDept = "HR"};

Now add this under a collection.

IList<Employee> empDetails = new List<Employee> {emp1, emp2 };

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      var emp1 = new Employee() { EID = 001, EmpName = "Tim", EmpDept = "Finance"};
      var emp2 = new Employee() { EID = 002, EmpName = "Tom", EmpDept = "HR"};
      IList<Employee> empDetails = new List<Employee> {emp1, emp2 };

      // Employee 1
      Console.WriteLine("Employee One...");
      Console.WriteLine(emp1.EID);
      Console.WriteLine(emp1.EmpName);
      Console.WriteLine(emp1.EmpDept);

      // Employee 2
      Console.WriteLine("Employee Two...");
      Console.WriteLine(emp2.EID);
      Console.WriteLine(emp2.EmpName);
      Console.WriteLine(emp2.EmpDept);
   }
}

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

Output

Employee One...
1
Tim
Finance
Employee Two...
2
Tom
HR

Updated on: 23-Jun-2020

627 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements