Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements