How to create a list of objects in C#

A list in C#, just like lists in other programming languages, is a collection of items that can be indexed, searched, sorted and manipulated. Since C# is an object-oriented programming language, knowing how to create a list of objects is vital to solving problems.

A list containing several objects of a class.
A list containing several objects of a class.

To create a list in C# from the built-in class definition of a list, import the following library the top of the code:

using System.Collections.Generic

The following code snippet outlines the method to create a list of objects:

using System;
using System.Collections.Generic;
public class employee
{
private string name;
private int age;
private string designation;
// constructor
public employee(string name, int age, string designation)
{
this.name = name;
this.age = age;
this.designation = designation;
}
// utility functions for the class
public string getName
{
get{return name;}
}
public int getAge
{
get{return age;}
}
public string getDesignation
{
get{return designation;}
}
}
public class main
{
public static void Main()
{
// create a list of type 'employee'
List<employee> employeeList = new List<employee>();
// populate the list with objects of 'employee'
employeeList.Add(new employee("John", 29, "Developer"));
employeeList.Add(new employee("Mike", 23, "Engineer"));
employeeList.Add(new employee("Alex", 29, "Manager"));
employeeList.Add(new employee("Smith", 29, "Intern"));
// printing out the list
foreach(var item in employeeList)
Console.WriteLine("Name: {0}, Age: {1}, Designation: {2}",item.getName,item.getAge,item.getDesignation);
}
}

Explanation

  • The employee class assigns values to name, age and designation, through its constructor in line 11.
  • Line 37 creates a list called employeeList (of datatype employee) and lines 37 to 42 add objects of the employee class to this list.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved