Say you want to add up a student’s grades. With what you know so far, you would create grade1, grade2, grade3, and so on. That works for five grades. It doesn’t work for fifty, and if you don’t know how many grades are coming, there is no way to declare the variables ahead of time.
That is what collections are for: a single variable that holds many values. Today we cover the three you will use most in C#: the array, the list and the dictionary. We also cover foreach, the loop I promised you in the previous chapter.
Arrays: a row of boxes with a fixed size
An array is a row of values of the same type. You declare one by putting [] after the type:
int[] grades = [90, 85, 77, 100, 68];
Console.WriteLine(grades[0]);
Console.WriteLine(grades[4]);
Console.WriteLine($"There are {grades.Length} grades");
grades[2] = 80;
Console.WriteLine(grades[2]);
90
68
There are 5 grades
80
int[] reads as “array of integers”. The values go between square brackets, separated by commas.
To reach a value you use its index, the position inside the brackets. And here is the part that trips up everyone at first: the first index is 0, not 1. In an array of five grades, the indexes go from 0 to 4. That is why grades[4] is the last one.
grades.Length tells you how many elements it has. With grades[2] = 80 you change the value at that position, the same way you assign a variable.
If you know how many elements you need but not their values yet, you can create an empty array with new:
int[] points = new int[3];
Console.WriteLine(points[0]);
0
Every position starts with the type’s default value: 0 for int, false for bool.
The key thing about an array is that its size never changes. If you created it with five slots, it has five slots forever. And if you try to read grades[5], the program compiles but crashes when it runs, with an error that starts like this:
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
You asked for position 5 and only positions 0 to 4 exist. In chapter 7 we learn to read these errors in full.
Walking an array with for
With the for loop from the previous chapter you can already walk through an array. The trick is that the counter i doubles as the index:
int[] grades = [90, 85, 77, 100, 68];
int sum = 0;
for (int i = 0; i < grades.Length; i++)
{
sum += grades[i];
}
Console.WriteLine($"Sum: {sum}");
Sum: 420
Look at the condition: i < grades.Length, with less than. If you write <=, the last attempt would be grades[5], and you already know what happens then.
foreach: looping without counting
Most of the time you don’t care about the index. You just want to visit each value. That is what foreach does:
int[] grades = [90, 85, 77, 100, 68];
int sum = 0;
foreach (int grade in grades)
{
sum += grade;
}
Console.WriteLine($"Sum: {sum}");
Sum: 420
It reads almost like English: “for each grade in grades, do this”. On every pass, grade takes the next value. There is no counter, no condition, and no way to run off the end of the array by accident.
There is one rule: inside the foreach you can’t assign a new value to grade. If you write grade = 0;, the compiler stops you with an error. If you need to change values in the array, use for with an index.
My rule of thumb: use foreach when you only read, and for when you need the position or want to modify.
List: a collection that grows
Arrays have a problem: you have to know the size up front. In real life you almost never do. A grocery list grows and shrinks. That is what List<T> is for:
List<string> groceries = new List<string>();
groceries.Add("rice");
groceries.Add("beans");
groceries.Add("milk");
Console.WriteLine($"You have {groceries.Count} items");
Console.WriteLine(groceries[0]);
groceries.Remove("beans");
Console.WriteLine($"Now you have {groceries.Count}");
foreach (string item in groceries)
{
Console.WriteLine($"- {item}");
}
You have 3 items
rice
Now you have 2
- rice
- milk
Let’s take it piece by piece:
List<string>reads as “list of strings”. Whatever goes between<and>is the type it holds. TheTinList<T>is a placeholder for the type you pick:List<int>,List<decimal>,List<bool>.new List<string>()creates the empty list.Addputs an element at the end.Counttells you how many there are. Watch out: arrays useLength, lists useCount. You will mix them up a few times, and the compiler will tell you.groceries[0]works just like with arrays, with indexes starting at 0.Removefinds the value and takes it out. If it isn’t there, nothing happens and the list stays the same.
Because you said the list holds string, the compiler won’t let you put anything else in it. If you write groceries.Add(5);, you get error CS1503: Argument 1: cannot convert from 'int' to 'string'. That is a good thing: the error shows up before the program runs, not after.
A list can also start with values, using the same brackets as the array:
List<int> numbers = [3, 1, 4];
numbers.Add(1);
Console.WriteLine(numbers.Count);
4
Array or list?
If the size is fixed and you know it ahead of time (days of the week, months of the year), an array is fine. If elements will come and go, use List. When in doubt, the list is almost always the more comfortable choice.
Dictionary: look things up by name, not by position
Lists and arrays give you values by position. But often you want to look up by something else: a person’s age by their name, a product’s price by its code. That is what a dictionary is for.
A dictionary stores pairs of a key and a value. Like a paper dictionary: you look up the word (the key) and find the definition (the value).
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Ana", 30);
ages.Add("Luis", 25);
Console.WriteLine(ages["Ana"]);
ages["Luis"] = 26;
ages["Marta"] = 41;
Console.WriteLine($"There are {ages.Count} people");
foreach (var pair in ages)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
30
There are 3 people
Ana: 30
Luis: 26
Marta: 41
Dictionary<string, int> has two types: the first is the key’s type (string, the name) and the second is the value’s type (int, the age).
There are two ways to store something:
Add("Ana", 30)adds a new pair. If the key already exists, the program crashes with an error saying an item with that key was already added. Keys can’t repeat.ages["Marta"] = 41with brackets is more flexible: if the key doesn’t exist, it creates it; if it exists, it changes the value. That is how we updated Luis’s age.
To read, ages["Ana"] gives you the value for that key.
In the foreach, each element is a pair with two parts: Key and Value. Its full type is KeyValuePair<string, int>, which is long, so I used var. One detail: don’t count on the dictionary handing back the pairs in the order you stored them. Here they came out in order, but the dictionary doesn’t promise it.
When the key isn’t there
Here is the trap. If you read a key that doesn’t exist, say ages["Pedro"], the program crashes with a KeyNotFoundException. You have two ways to avoid it:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Ana"] = 30;
if (ages.ContainsKey("Pedro"))
{
Console.WriteLine(ages["Pedro"]);
}
else
{
Console.WriteLine("I don't know Pedro");
}
if (ages.TryGetValue("Ana", out int age))
{
Console.WriteLine($"Ana is {age}");
}
I don't know Pedro
Ana is 30
ContainsKey asks whether the key exists and gives you back true or false. Pair it with an if and you’re done.
TryGetValue does both at once: it asks and, if the key exists, it leaves the value in the variable you put after out. If that looks familiar, it is because it works just like int.TryParse from chapter 3: it returns true or false, and the result arrives through the out. If the key doesn’t exist, age ends up as 0.
Use ContainsKey when you only want to know if something is there. Use TryGetValue when you also need the value.
Mini-exercise: word counter
Write a program that asks for a sentence and says how many times each word appears.
Type a sentence: the dog eats and the dog sleeps
the: 2
dog: 2
eats: 1
and: 1
sleeps: 1
Distinct words: 5
You need two new string tools, each one line:
sentence.ToLower()turns everything lowercase, so “The” and “the” count as the same word.sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries)cuts the sentence at each space and gives you back astring[]with the words.RemoveEmptyEntriesavoids empty words if someone types two spaces in a row.
The hint: a Dictionary<string, int> where the key is the word and the value is how many times you’ve seen it. Try to solve it before looking at the solution.
Suggested solution
Console.Write("Type a sentence: ");
string sentence = Console.ReadLine() ?? "";
string[] words = sentence.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (string word in words)
{
if (counts.ContainsKey(word))
{
counts[word]++;
}
else
{
counts[word] = 1;
}
}
foreach (var pair in counts)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
Console.WriteLine($"Distinct words: {counts.Count}");
The ?? "" after Console.ReadLine() means “if no text came in, use an empty string”. That way sentence always has a value.
The heart of it is the first foreach. If the word is already in the dictionary, you add one with ++, the same one you use in loops. If it isn’t, you store it with a 1.
With TryGetValue you can write it shorter. Replace the first foreach with this one:
foreach (string word in words)
{
counts.TryGetValue(word, out int times);
counts[word] = times + 1;
}
If the word isn’t there, times is 0 and you store it with 1. If it is, you get the current count and add one. Both versions do the same thing; pick the one that reads more clearly to you.
To push yourself: try “Hello, hello”. You will see that hello, and hello count as different words because of the comma. How would you fix it?
What you learned
- An array (
int[]) holds several values of the same type, with a fixed size. Its size is inLength. - Indexes start at 0. Going out of range crashes the program.
foreachwalks any collection without a counter. Use it to read; useforif you need the position or want to modify.List<T>grows and shrinks withAddandRemove. Its size is inCount.Dictionary<TKey, TValue>stores key and value pairs and looks things up by key.- Before reading a key that might not exist, use
ContainsKeyorTryGetValue.
Your programs can now handle lots of data, and they are getting long. In the next chapter we learn to split them into named pieces: methods.
Got questions?
If something didn’t click or your word counter does something strange, send me a DM on Instagram or ask in the Discord community. Send your code and we’ll look at it together.
