.NET Core API Documentation

Class List<T>

Represents a strongly typed list of objects that can be accessed by index. Provides methods for manipulating the list.

Namespace: System.Collections.Generic
Assembly: System.Collections.dll

Summary

The List<T> generic collection is the programmatic representation of a dynamic array. It can hold objects of any type, from any non-private code. The size of the List<T> is automatically increased as elements are added.

Each item in the list is an object. You can access any member of the item programmatically as long as you specify the correct index of the item.

The List<T> class provides performance that is similar to the ArrayList class. It is generally recommended to use the List<T> generic collection when programming in C# because it provides better performance and type safety.

Syntax

                
                    public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
                
            

Type Parameters

Constructors

Properties

Methods

Examples

Adding and Accessing Elements


using System;
using System.Collections.Generic;

List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");

Console.WriteLine("Elements:");
foreach (string name in names)
{
    Console.WriteLine(name);
}

Console.WriteLine($"Element at index 1: {names[1]}"); // Output: Bob
            

Removing Elements


using System;
using System.Collections.Generic;

List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };

numbers.Remove(30); // Removes the first occurrence of 30
numbers.RemoveAt(0); // Removes the element at index 0 (which is 10)

Console.WriteLine("Updated numbers:");
foreach (int num in numbers)
{
    Console.WriteLine(num); // Output: 20, 40, 50
}
            

Remarks

The List<T> class implements the generic IList<T>, ICollection<T>, and IEnumerable<T> interfaces, and also the non-generic IList, ICollection, and IEnumerable interfaces.

If the capacity of the List<T> is insufficient to accommodate the new element, the elements are copied to a new underlying array before the new element is added.

Exceptions

ArgumentNullException

Thrown when a collection is passed to a constructor or method that does not allow null references.

ArgumentOutOfRangeException

Thrown when an index is outside the valid range of the list.

NotSupportedException

Thrown when an operation is attempted that is not supported by the list (e.g., modifying a read-only list).