How to Create List of Objects in C# Easily
In C#, you create a list of objects using the
List<T> class where T is your object type. First, define a class for your objects, then create a List<YourClass> and add instances to it.Syntax
To create a list of objects in C#, you use the generic List<T> class from System.Collections.Generic. Replace T with your class name. You can then add objects to this list.
List<YourClass> listName = new List<YourClass>();creates an empty list.listName.Add(objectInstance);adds an object to the list.
csharp
using System.Collections.Generic; public class Person { public string Name { get; set; } public int Age { get; set; } } // Create a list of Person objects List<Person> people = new List<Person>(); // Add a new Person to the list people.Add(new Person { Name = "Alice", Age = 30 });
Example
This example shows how to define a Person class, create a list of Person objects, add multiple people, and print their details.
csharp
using System; using System.Collections.Generic; public class Person { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { List<Person> people = new List<Person>(); people.Add(new Person { Name = "Alice", Age = 30 }); people.Add(new Person { Name = "Bob", Age = 25 }); people.Add(new Person { Name = "Charlie", Age = 35 }); foreach (var person in people) { Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } }
Output
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 35
Common Pitfalls
Common mistakes when creating lists of objects include:
- Forgetting to include
using System.Collections.Generic;which is needed forList<T>. - Trying to add objects of the wrong type to the list.
- Not initializing the list before adding objects, causing a
NullReferenceException.
Always initialize your list with new List<T>() before adding items.
csharp
using System.Collections.Generic; public class Car { public string Model { get; set; } } // Wrong: list not initialized List<Car> cars; cars = new List<Car>(); // Added initialization to fix error cars.Add(new Car { Model = "Tesla" }); // This works now // Right: list initialized List<Car> cars2 = new List<Car>(); cars2.Add(new Car { Model = "Tesla" }); // Works fine
Quick Reference
Summary tips for creating and using lists of objects in C#:
- Use
List<T>fromSystem.Collections.Generic. - Initialize the list before adding objects.
- Add objects using
Add()method. - Use
foreachto loop through the list.
Key Takeaways
Use List to create a list of objects where T is your class type.
Always initialize your list with new List() before adding objects.
Add objects to the list using the Add() method.
Use foreach loops to access each object in the list easily.
Include using System.Collections.Generic to use List.