Start learning free

LESSON 88 OF 347 · ARRAYS I

Lists in C#: Creating and Initializing List<T>

Lesson Read the full explanation

A big limitation of static arrays in C# is the fact that once the array is created, it has a fixed size.

The List overcomes this limitation by having variable size and allowing for elements to be added or removed.


Creation:

We create an List by using the keywords new and List, then writing the type of the elements inside <> followed by paranthesis:

new List<string>();

This code creates an empty List where each item is a string.


Casting:

A good practice is to cast the created List in its interface by using a List variable and specifying there the type of the elements, like this:

List<string> sandwich = new List<>();

Initialization:

You can also initialize an List at creation by using the List.of() function and put a comma between each entry, like this:

List<string> sandwich = new List<>(
    List.of("peanut butter", "jelly", "bread")
);

We created an List named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".


Assignment
Follow the Coding Tutorial and let's create some ArrayLists!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    C# · ARRAYS I

    Arrays in C#, explained

    Why use a List

    An array's length is fixed when it is created. A List<T> removes that limit: it can grow when you add items and shrink when you remove them. It lives in the System.Collections.Generic namespace, and T is the type of the elements, so List<string> holds strings and List<int> holds ints.

    Some courses call this structure an "ArrayList" because it keeps its items in an array internally. In C# the class you use is List<T>. A separate, older class named ArrayList also exists, but it stores plain objects without a declared element type, so new code uses List<T> instead.

    Creating an empty list

    Give the element type inside angle brackets after List, and call the constructor with parentheses:

    List<string> sandwich = new List<string>();
    

    This creates an empty list of strings. The variable's type is written on the left, and the same element type is repeated after new. C# can also infer it for you with the shorter form List<string> sandwich = new();.

    Creating a list with values

    There are two common ways to fill a list at creation.

    A collection initializer

    Put the values in braces after the constructor:

    List<string> sandwich = new List<string> {"peanut butter", "jelly", "bread"};
    

    Copying from an array

    The List<T> constructor accepts any existing sequence of items and copies them into the new list. That includes an array:

    List<string> sandwich = new List<string>(
        new[] {"peanut butter", "jelly", "bread"}
    );
    

    Here new[] {...} builds an array and the compiler works out that its element type is string. The list then holds its own copy of the three items, so changing the list later doesn't touch the array. The lesson's exercise uses this second form.

    Both styles give a list with three items that can grow. There is no List.of(...) in C#.

    Arrays or lists

    Use an array when the number of items is known and stays the same, such as the seven days of a week. Use a list when the number changes while the program runs, for example when you collect results one by one. A list also offers helpful methods, such as Add, Remove and Contains. You read and write both with the same square brackets, so most code looks alike.

    Because a list can start empty and grow, you will often see the empty form followed by calls to Add:

    List<int> scores = new List<int>();
    scores.Add(10);
    scores.Add(20);
    Console.WriteLine(scores.Count);  // 2
    

    The exercise, step by step

    1. The fruits. Declare a List<string> named fruits and pass the constructor an array containing "mango", "kiwi" and "grapefruit".
    2. The ages. Declare a List<int> named ages built from 14, 32, 50 and 21. The element type has to match the values, so whole numbers need int.
    List<string> fruits = new List<string>(
        new[] {"mango",
            "kiwi",
        "grapefruit"}
    );
    List<int> ages = new List<int>(new[] {14, 32, 50, 21});
    

    The odd line breaks in the first declaration don't matter to the compiler, which ignores extra whitespace between tokens.

    Common mistakes

    • Forgetting the using directive. Outside the lesson, a file needs using System.Collections.Generic; at the top (or implicit usings, which many project templates enable) before List<T> is recognised.
    • Forgetting the parentheses. new List<string> followed by nothing is an error. Add (), or follow the type with an initializer in braces.
    • Mismatched types. A List<int> can't be built from an array of strings, and new List<int> {"a"} doesn't compile.
    • Using parentheses where the initializer needs braces. new List<int>(1, 2, 3) is wrong. Pass one collection to the constructor, or put the values in braces.
    • Mixing up array and list size words. Arrays report Length, lists report Count. A later lesson covers this.

    Key takeaways

    • List<T> is C#'s resizable collection; the type in angle brackets is the element type.
    • Create one with new List<T>(), with braces of values, or by passing an existing array to the constructor.
    • Copying from an array gives the list its own independent items.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free