← Back to C# Course | Chapter 9: Collections | Lesson 2 of 7

List<T>

A List is a stretchy array that grows and shrinks as you add or remove things. It is like a backpack that expands to fit more books.

In this page:

  1. List<T>
Syntax
csharp
List<type> listName = new List<type>();
listName.Add(item);
listName.Remove(item);
listName[0];
listName.Count;

List<T>

List<T> is a dynamically resizable collection from System.Collections.Generic, unlike fixed-size arrays. You can add, remove, and search elements, and it grows automatically as needed. It's the most commonly used general-purpose collection in C#.

Note: Prefer List<T> over arrays whenever the number of elements can change at runtime.

Example: List<T>

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<string> names = new List<string> { "Amy", "Bo" };
        names.Add("Cy");
        names.Remove("Bo");

        Console.WriteLine(names.Count);
        foreach (string name in names)
        {
            Console.WriteLine(name);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Removing items from a list inside a foreach, which throws InvalidOperationException.
  2. Using an index equal to Count, which throws ArgumentOutOfRangeException.
  3. Forgetting using System.Collections.Generic; when implicit usings are disabled.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.