×

c# · level 2 · unit 1 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A grows every time you add to it.

An array has a fixed size: you choose how many slots before you start. A List grows instead. Start it empty, then add as many items as you like. Lists live in a toolbox called System.Collections.Generic, so bring it in with a second using line.

List<string> pets = new List<string>(); makes an empty list of strings. The , < and >, hold the type of item the list keeps. .Add("cat") puts an item on the end, and its , pets.Count, says how many items it holds right now.

Read an item by its index, as with an array: pets[0]. You can also fill a list as you make it, with a : new List<string> { "cat", "dog" }. A list prints only its type, so use string.Join to see the items.

using System;
using System.Collections.Generic;

List<string> pets = new List<string>();
pets.Add("cat");
pets.Add("dog");
pets.Add("hamster");
Console.WriteLine(pets.Count);
Console.WriteLine(pets[0]);
Console.WriteLine(string.Join(", ", pets));

Arrays count with .Length, lists count with .Count.