CodeBlanks Logo Icon CodeBlanks

Listing tasks

C# course · Beginner · Lesson 85/116

Learn to print tasks formatted with ListTasks.

Listing tasks

After adding tasks to the list, we want to see them. The ListTasks method walks through all tasks with foreach and prints each one's Title to the screen.

The method signature: static void ListTasks(List<Task> tasks). The body is the loop foreach (Task t in tasks) { Console.WriteLine(t.Title); }. This structure iterates the list from start to end.

Iterating with foreach

The foreach loop walks through all elements of a collection in order. foreach (Task t in tasks) assigns each task to the variable t and runs the loop body.

This removes the risk of an indexing mistake; you do not have to manage an index variable i as in a for loop. It is ideal for a one-way pass over a list.

Exercise ListTasks method

Write the body of ListTasks: foreach (Task t in tasks) { Console.WriteLine(t.Title); }. In Main, add two tasks (AddTask(tasks, "Buy bread") and AddTask(tasks, "Buy milk")) then call ListTasks(tasks).

Show example solution
Add foreach (Task t in tasks) { Console.WriteLine(t.Title); } to the ListTasks body, write ListTasks(tasks); in Main.
Example solution:
using System;
using System.Collections.Generic;

class Task
{
    public string Title;
    public bool IsDone;
}

class Program
{
    static void AddTask(List<Task> tasks, string title)
    {
        tasks.Add(new Task { Title = title, IsDone = false });
    }

    static void ListTasks(List<Task> tasks)
    {
        // Print each task's title with foreach
        foreach (Task t in tasks)
        {
            Console.WriteLine(t.Title);
        }
    }

    static void Main()
    {
        List<Task> tasks = new List<Task>();
        AddTask(tasks, "Buy bread");
        AddTask(tasks, "Buy milk");
        // Add a ListTasks call
        ListTasks(tasks);
    }
}

Test yourself

  1. What does tasks[0].Title print?

    List<Task> tasks = new List<Task>();
    tasks.Add(new Task { Title = "Buy bread", IsDone = false });
    tasks.Add(new Task { Title = "Buy milk", IsDone = false });
    Console.WriteLine(tasks[0].Title);
    • Buy milk
    • Buy bread
    • Empty
    • 2
    Show answer

    Buy bread — Correct. The first added task has index 0; its Title is "Buy bread".

  2. foreach loop

    foreach (____)
    {
        Console.WriteLine(t.Title);
    }
    Show answer
    foreach (Task t in tasks)
    {
        Console.WriteLine(t.Title);
    }
  3. Match each expression to its meaning

    foreach
    Iterate each
    t.Title
    Task title
    Console.WriteLine
    Print
    tasks.Count
    Total tasks

All lessons in Beginner