← All lessons

Level 1 / C# Fundamentals / fundamental 6 of 7

Arrays and lists

Store many values in arrays and List<T>, read and change items by index, and loop over them.

Most real data comes in groups: crew members, sensor readings, scores. Arrays hold a fixed number of items; lists grow and shrink as you add and remove. These reps pair each collection with the loops and methods you have already drilled.

Understand the idea

Indexes start at 0

scores[0] is the first item and, in a three-item array, scores[2] is the last. Reading scores[3] throws an IndexOutOfRangeException at run time, not a compile error.

Arrays are fixed, lists grow

An array's size is set when it is created and is read with .Length. A List<T> starts empty, grows with Add, shrinks with Remove, and reports its size with .Count.

The type goes in angle brackets

List<string> is a list that only holds strings, and List<int> only holds ints. The compiler stops you from adding the wrong type, the same way it does for a single variable.

English to C#

“Make a List of strings called names.”

List<string> names = new List<string>();
List<string>
the type: a list that holds strings
names
the variable name
new List<string>()
create the empty list

Rep 1 of 13

Copy it

In English

Make an int array called scores holding 90, 85, and 72.

Type the code shown below. Watch it turn green as you go.

int[] scores = { 90, 85, 72 };

Waiting for you to type · 0 of 13 pieces

Ctrl+Enter checks or moves on. Tab indents. Paste is off on purpose: your hands are learning this too.

Reps

0 of 13 done

Reps unlock in order, because each one builds on the last.

How your code is checked

Drills compare what you type with known-correct C#, token by token. Spacing, line breaks, and comments do not matter; spelling, case, and punctuation do. It is not a compiler, so it accepts the listed spellings of each answer and nothing else.

Try it in a real .NET project

Keep reading names with Console.ReadLine into a List<string> until the user enters a blank line, then print how many there are and each one with its position number. Try reading names[names.Count] and read the exception message.

Check your understanding

Why does C# have both arrays and List<T>, and which would you pick for a list of crew members who join and leave during a shift?

Show the explanation

Arrays have a fixed size and are slightly simpler and faster, which suits data whose size never changes. A List<T> grows and shrinks with Add and Remove, so a crew roster that changes during a shift should be a List<string>.

Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.