Introduction to List<T>

A List<T> holds values of one type and grows and shrinks for you; the T says which type, like int or string.

Apprentice · C# · Updated

After this lesson you can

  • Explain how a List<T> manages its size for you, and what the T means

Key takeaways

  • A List<T> keeps its values in an array and manages it for you: it grows when you add, shifts when you insert and closes the gap when you remove.
  • The T is the type the list holds, chosen in angle brackets: List<string> is a list of strings, and a List<int> won't accept text.
  • Add puts a value at the end of a list, and Count gives its size, where an array uses Length.
  • A list can start empty, as in new List<string>(), or with values, as in List<int> scores = [21, 14, 35];.

A List<T> is a class that does all the tedious work from the last lesson for you. Inside, it still keeps its values in an array, but it manages that array itself: it grows when you add, shifts when you insert, and closes the gap when you remove.

Array vs List

Using an array directly is like parking your own car in a crowded lot: you have to find a free space and squeeze in.

Cars parked in a crowded parking lot

Using a List<T> is like handing your keys to a valet. Your car still gets parked, but the details aren't your problem.

A valet parking sign

What the T means

The T in List<T> stands for type: a list holds values of one type, and you choose which in angle brackets when you make it.

List<string> names = new List<string>();
List<int> scores = new List<int>();
List<decimal> prices = new List<decimal>();

List<string> reads as "a list of strings". A class like this, which works with whatever type you give it, is called generic. The type is checked like any other: a List<int> won't accept text.

A list that grows

List<string> cart = new List<string>();
cart.Add("milk");
cart.Add("eggs");
cart.Add("bread");
cart.Add("butter");

Console.WriteLine(quot;Items: {cart.Count}");
Console.WriteLine(string.Join(", ", cart));
Items: 4
milk, eggs, bread, butter

No new arrays, no copying: Add does it. A list's size is Count, where an array's is Length.

Making lists

There are a few ways to start a list, all common:

List<string> empty = new List<string>();
List<string> teams = new List<string> { "Georgia", "Alabama" };
List<int> scores = [21, 14, 35];
var names = new List<string>();

Console.WriteLine(quot;{empty.Count} {teams.Count} {scores.Count} {names.Count}");
0 2 3 0

You'll need List<T> everywhere in C#: lists of products in a store, rows read from a database, results returned by a web API.

Check yourself

1 question to try on the lesson page.

So what

List<T> is the collection you'll reach for most: one type of value, any number of them, and none of the bookkeeping.

Key terms

Cheat sheets