C#
Completing tasks
Learn to update task status with CompleteTask.
Completing tasks
To mark a task as done we will write the CompleteTask method. This method sets the IsDone field of the task at a given index to true.
The method signature: static void CompleteTask(List<Task> tasks, int index). The body is a single line: tasks[index].IsDone = true;. Here tasks[index] gives the task, .IsDone gives its status field.
Access by index
The list is accessed with the indexer tasks[i]; the first task is tasks[0], the second tasks[1]. Indices start at 0 and go up to tasks.Count - 1.
To update a task's field you first access it then assign: tasks[0].IsDone = true;. The syntax is similar to modifying an array element; you only add a dot to select a field.
Exercise CompleteTask method
Write the body of CompleteTask: tasks[index].IsDone = true;. In Main, add two tasks, call ListTasks(tasks), then call CompleteTask(tasks, 0) and print tasks[0].IsDone with Console.WriteLine.
Show example solution
Add tasks[index].IsDone = true; to the CompleteTask body, write CompleteTask(tasks, 0); Console.WriteLine(tasks[0].IsDone); 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)
{
foreach (Task t in tasks)
{
Console.WriteLine(t.Title);
}
}
static void CompleteTask(List<Task> tasks, int index)
{
// Mark the task as done
tasks[index].IsDone = true;
}
static void Main()
{
List<Task> tasks = new List<Task>();
AddTask(tasks, "Buy bread");
AddTask(tasks, "Buy milk");
ListTasks(tasks);
// Add a CompleteTask call and print the status
CompleteTask(tasks, 0);
Console.WriteLine(tasks[0].IsDone);
}
}
Test yourself
-
What is printed after IsDone = true?
List<Task> tasks = new List<Task>();
tasks.Add(new Task { Title = "Buy bread", IsDone = false });
tasks[0].IsDone = true;
Console.WriteLine(tasks[0].IsDone);
Show answer
True — Correct. After IsDone = true, Console.WriteLine prints True.
-
Update status
tasks[____].IsDone = true;
Console.WriteLine(tasks[0].IsDone);
Show answer
tasks[0].IsDone = true;
Console.WriteLine(tasks[0].IsDone);
-
Match each expression to its meaning
- tasks[0]
- First task
- tasks[i]
- i-th task
- .IsDone = true
- Mark done
- tasks.Count
- Task count
Next lesson: Putting it together