Tutorials / C# for Beginners / Arrays and List of T

Arrays and List of T

14 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. Expense tracker, part 2: the menu and summaries

One variable, many values

Suppose you want to keep five exam scores. Five variables named score1 to score5 would be silly. A collection holds them all under one name. C# has several collection types. Two matter most for a beginner: the array and the list.

Arrays

An array has a fixed size. You choose the size when you create it, and it never changes. Items are numbered from zero.

int[] scores = new int[5];          // five zeros
scores[0] = 80;
string[] days = { "Mon", "Tue", "Wed" };
Console.WriteLine(days[2]);          // Wed
Console.WriteLine(days.Length);      // 3

Reading days[3] would throw an IndexOutOfRangeException, because the valid positions are 0, 1 and 2. This is the most common array error.

List of T

Most of the time you do not know the size in advance. A List<T> grows and shrinks as you add and remove items. The T is a placeholder for the type of item. List<string> is a list of strings, List<int> a list of ints. You type the type once and the compiler stops you from adding the wrong thing. The angle brackets are part of a feature called generics, which you can study in the advanced course.

var shopping = new List<string>();
shopping.Add("Milk");
shopping.Add("Eggs");
shopping.Add("Bread");
shopping.Add("Tea");

Console.WriteLine($"Items: {shopping.Count}");

shopping.Remove("Eggs");
shopping.Insert(0, "Rice");

foreach (string item in shopping)
{
    Console.WriteLine($"- {item}");
}

Console.WriteLine(shopping.Contains("Milk"));      // True
Console.WriteLine(shopping.IndexOf("Tea"));        // position or -1

shopping.Sort();
Console.WriteLine(string.Join(", ", shopping));

// A list of numbers with some statistics
var scores = new List<int> { 80, 65, 92, 71, 58 };
int total = 0;
foreach (int s in scores)
{
    total += s;
}
double average = (double)total / scores.Count;
Console.WriteLine($"Average: {average:F1}");
Console.WriteLine($"Highest: {scores.Max()}, lowest: {scores.Min()}");

// Remove everything below 60
scores.RemoveAll(s => s < 60);
Console.WriteLine(scores.Count);

Walking through it

We start with an empty list and call Add four times. Count is the number of items. For arrays the same thing is called Length. That inconsistency is historical, and you simply have to remember it.

Remove("Eggs") finds the first item equal to "Eggs" and deletes it. The items after it shift down. Insert(0, "Rice") puts an item at the front and shifts everything else up. Both of these touch many items, which is fine for small lists.

The foreach loop prints every item. You cannot change the list inside it.

The average uses a cast, (double)total. Without it, dividing an int by an int gives an int, and the decimals vanish. This is the integer-division trap from the types lesson.

Max and Min come from LINQ, a set of helper methods for collections. They work because of the implicit using lines in the project. Finally, RemoveAll(s => s < 60) removes every item for which the little function is true. The arrow => makes a lambda. Read it as "s such that s is below 60". You will meet lambdas again later. For now just copy the shape.

Array or list?

Use a list by default. Use an array when the size is truly fixed, such as the seven days of a week, or when a method you are calling requires one. Lists cost slightly more memory, but you will not notice that in ordinary programs.

Common mistakes

  • Counting from one. The first item is at position 0 and the last is at Count - 1.
  • Using Length on a list or Count on an array. The compiler will tell you.
  • Modifying a list during foreach. Loop over a copy or use RemoveAll.
  • Forgetting that lists hold references. If you store objects in a list, changing an object changes it everywhere it appears. We return to this in the classes lesson.

Try it yourself

  1. Create a List<string> of five friends' names. Print them sorted, then print only the names that start with a given letter typed by the user.
  2. Ask the user to enter numbers until they type "done". Store them in a list and print the sum and the average.
  3. Find the second-largest number in a list without using a ready-made method for it.
csharp
var shopping = new List<string>();
shopping.Add("Milk");
shopping.Add("Eggs");
shopping.Add("Bread");
shopping.Add("Tea");

Console.WriteLine($"Items: {shopping.Count}");

shopping.Remove("Eggs");
shopping.Insert(0, "Rice");

foreach (string item in shopping)
{
    Console.WriteLine($"- {item}");
}

Console.WriteLine(shopping.Contains("Milk"));      // True
Console.WriteLine(shopping.IndexOf("Tea"));        // position or -1

shopping.Sort();
Console.WriteLine(string.Join(", ", shopping));

// A list of numbers with some statistics
var scores = new List<int> { 80, 65, 92, 71, 58 };
int total = 0;
foreach (int s in scores)
{
    total += s;
}
double average = (double)total / scores.Count;
Console.WriteLine($"Average: {average:F1}");
Console.WriteLine($"Highest: {scores.Max()}, lowest: {scores.Min()}");

// Remove everything below 60
scores.RemoveAll(s => s < 60);
Console.WriteLine(scores.Count);

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account