Understanding List<T> in C# Collections
Quick Answer
List<T> in C# is a generic collection that provides a dynamic array to store elements. It allows adding, removing, and accessing items efficiently, making it ideal for scenarios where the collection size changes dynamically.
Learning Objectives
- Explain the purpose of List<T> in a practical learning context.
- Identify the main ideas, terms, and decisions involved in List<T>.
- Apply List<T> in a simple real-world scenario or practice task.
Introduction to List<T> in C#
In C#, collections are essential for storing and managing groups of objects. Among these, List<T> is one of the most commonly used generic collections.
List<T> provides a flexible and dynamic array that can grow or shrink as needed, unlike fixed-size arrays.
This tutorial will guide you through the basics of List<T>, its key features, and practical usage examples.
"List<T> offers the power of arrays with the flexibility of dynamic resizing."
What is List<T>?
List<T> is a generic collection class in the System.Collections.Generic namespace. It stores elements of a specified type T and manages the size dynamically.
Unlike arrays, List<T> can automatically resize itself when elements are added or removed, making it more versatile for many programming scenarios.
- Generic: works with any data type specified by T.
- Resizable: grows or shrinks as elements are added or removed.
- Indexed: supports accessing elements by index.
- Supports common collection operations like Add, Remove, and Contains.
Creating and Initializing a List<T>
You can create a List<T> by specifying the type of elements it will hold. Initialization can be empty or with an initial collection.
Here are some common ways to create a List<T>:
- Empty list: List<int> numbers = new List<int>();
- With initial capacity: List<string> names = new List<string>(10);
- From an existing collection: List<char> letters = new List<char>(existingArray);
Common List<T> Methods
List<T> provides many useful methods to manipulate the collection. Understanding these methods is key to effective use.
- Add(T item): Adds an element to the end of the list.
- Remove(T item): Removes the first occurrence of a specific object.
- RemoveAt(int index): Removes the element at the specified index.
- Insert(int index, T item): Inserts an element at the specified index.
- Contains(T item): Checks if the list contains a specific element.
- Clear(): Removes all elements from the list.
- Count property: Gets the number of elements in the list.
Example: Using List<T> in C#
Let's look at a simple example demonstrating how to create a List of strings, add items, and iterate through them.
Practical Example
This example creates a List of strings, adds three fruit names, and prints each fruit to the console.
Examples
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}This example creates a List of strings, adds three fruit names, and prints each fruit to the console.
Best Practices
- Use List<T> when you need a dynamic collection that changes size frequently.
- Prefer List<T> over arrays when you need to add or remove elements dynamically.
- Use the Count property instead of Length to get the number of elements in a List.
- Avoid frequent resizing by initializing List<T> with an estimated capacity if known.
- Use foreach loops for safe and readable iteration over List<T>.
Common Mistakes
- Confusing List<T> with arrays and expecting fixed size behavior.
- Using Remove inside a foreach loop which can cause runtime exceptions.
- Not checking if an element exists before removing it, which can lead to unexpected behavior.
- Assuming List<T> is thread-safe without synchronization in multi-threaded scenarios.
Hands-on Exercise
Manipulate a List of Integers
Create a List<int>, add numbers 1 to 5, remove the number 3, and print the remaining elements.
Expected output: 1 2 4 5
Hint: Use Add, Remove, and foreach to complete the task.
Initialize List with Collection
Initialize a List<string> using an existing array of strings and print all elements.
Expected output: Prints all elements from the array.
Hint: Use the List<T> constructor that accepts IEnumerable<T>.
Interview Questions
What is the difference between an array and a List<T> in C#?
InterviewAn array has a fixed size and cannot be resized after creation, while List<T> is a dynamic collection that can grow or shrink as needed.
How do you add an element to a List<T>?
InterviewUse the Add(T item) method to append an element to the end of the List<T>.
Is List<T> thread-safe?
InterviewNo, List<T> is not thread-safe. You need to implement synchronization when accessing it from multiple threads.
MCQ Quiz
1. What is the best first step when learning List<T>?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce List<T>?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. List<T> in C# is a generic collection that provides a dynamic array to store elements.
B. List<T> never needs examples
C. List<T> is unrelated to practical work
D. List<T> should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- List<T> in C# is a generic collection that provides a dynamic array to store elements.
- It allows adding, removing, and accessing items efficiently, making it ideal for scenarios where the collection size changes dynamically.
- In C#, collections are essential for storing and managing groups of objects.
- Among these, List<T> is one of the most commonly used generic collections.
- List<T> provides a flexible and dynamic array that can grow or shrink as needed, unlike fixed-size arrays.
Summary
List<T> is a versatile and widely used generic collection in C# that provides dynamic resizing and easy management of elements.
It supports many useful methods for adding, removing, and searching elements, making it suitable for most collection needs.
Understanding List<T> is fundamental for effective C# programming and working with collections.
Frequently Asked Questions
Can List<T> store duplicate elements?
Yes, List<T> allows duplicate elements and preserves the order of insertion.
How do I access an element at a specific index in List<T>?
You can access elements using the indexer syntax: list[index].
What happens if I try to access an index out of range in List<T>?
An ArgumentOutOfRangeException is thrown if you access an invalid index.
What is List<T>?
List<T> in C# is a generic collection that provides a dynamic array to store elements.
Why is List<T> important?
It allows adding, removing, and accessing items efficiently, making it ideal for scenarios where the collection size changes dynamically.
How should I practice List<T>?
In C#, collections are essential for storing and managing groups of objects.

