c# · level 2 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The queue keeps growing. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
List<string> queue = new List<string> { "Amir", "Bella" };
Console.WriteLine(queue.Count);
queue.Add("Chen");
Console.WriteLine($"{queue[queue.Count - 1]} is last of {queue.Count}");
your turn
Your turn. Write a shopping list.
Put two things in the collection initialiser on line 4, then add a third on line 5. Press run to see how many things you need.
output
press run to see what happens
fix it
The guest count will not work. Can you fix it?
output
press run to see what happens
- C# says
CS1061on line 5: aListhas noLength. What does a list use to count its items? - Arrays count with
Length, but lists count with a different word. - Change
guests.Lengthtoguests.Counton line 5, then press run.
nailed it
your list grows as you go. :D
- A
Listgrows every time you.Addan item. .Countsays how many items it holds.- Use
string.Jointo print the items themselves.
new words in your collection
- List
- angle brackets
- Count
- collection initialiser
This lesson isn’t saved. A free account remembers every lesson you finish.