Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

List<T> — a resizable generic list

List<T> in System.Collections.Generic stores elements of a specified type in an ordered, mutable collection. The Add method appends an element, while the Count property reports the current number of elements, not the list's capacity.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

List<T> items = new List<T>();
items.Add(value);
int count = items.Count;
T first = items[0];

List<T> in System.Collections.Generic is a mutable, array-backed list whose capacity grows when needed. The parameter T specifies the element type, for example List<string>. The list allows duplicates and does not sort elements automatically. Indexes start at zero; the valid range is 0 <= index < Count.

List<T>.Add(T item) appends one element and returns void. After a successful addition, Count increases by one. With spare capacity, the operation costs O(1); when the array must grow and existing elements must be copied, it costs O(n), where n is the previous Count.

List<T>.Count is a read-only int property, accessed without parentheses: names.Count. Reading it costs O(1). Count means the number of stored elements, whereas Capacity means the number that fit without resizing the array. new List<string>(4) creates an empty list with room for four elements; it does not create four elements.

The example demonstrates an empty list, three Add calls, a duplicate, and indexed access. These APIs are available in .NET 10 and do not require preview language features. Sharing a list across threads with modifications requires synchronization; instance members do not guarantee thread safety.

Examples

using System;
using System.Collections.Generic;

internal static class Program
{
    private static void Main()
    {
        List<string> names = new List<string>(4);
        Console.WriteLine($"Count: {names.Count}");

        names.Add("Ada");
        names.Add("Linus");
        names.Add("Ada");

        Console.WriteLine($"Count: {names.Count}");
        Console.WriteLine($"First: {names[0]}");
        Console.WriteLine(string.Join(", ", names));
    }
}

Result

Count: 0
Count: 3
First: Ada
Ada, Linus, Ada

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources