C#
Adding tasks
Learn to add tasks to the list with the AddTask method.
Adding tasks
Now we will write the AddTask method. Its job is to create a new Task, set its title, and add it to the list. This way the main program does not have to write new Task() over and over.
The method signature: static void AddTask(List<Task> tasks, string title). The body uses an object initializer new Task { Title = title, IsDone = false } and adds it with tasks.Add(...).
List<Task> and initializer
To hold the tasks we use a List<Task> collection. This list is dynamically sized; it grows with each Add. An empty list is declared with new List<Task>().
An object initializer creates a class instance and fills its fields in one line: new Task { Title = "Buy bread", IsDone = false }. This is shorter than separate assignment statements.
Exercise AddTask method
Write the body of the AddTask method: tasks.Add(new Task { Title = title, IsDone = false });. In Main, call AddTask(tasks, "Buy bread") and print tasks.Count with Console.WriteLine.
Show example solution
Add tasks.Add(new Task { Title = title, IsDone = false }); to the AddTask body. In Main write AddTask(tasks, "Buy bread"); Console.WriteLine(tasks.Count);.
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)
{
// Create a new Task and add it to the list
tasks.Add(new Task { Title = title, IsDone = false });
}
static void Main()
{
List<Task> tasks = new List<Task>();
// Add an AddTask call and print the count
AddTask(tasks, "Buy bread");
Console.WriteLine(tasks.Count);
}
}
Test yourself
-
What does tasks[1].Title print after two adds?
List<Task> tasks = new List<Task>();
tasks.Add(new Task { Title = "Buy milk", IsDone = false });
tasks.Add(new Task { Title = "Buy bread", IsDone = false });
Console.WriteLine(tasks[1].Title);
Show answer
Buy bread — Correct. The second added task has index 1; its Title is "Buy bread".
-
Add call
List<Task> tasks = new List<Task>();
____
Console.WriteLine(tasks.Count);
Show answer
List<Task> tasks = new List<Task>();
tasks.Add(new Task { Title = "Buy milk", IsDone = false });
Console.WriteLine(tasks.Count);
-
Match each expression to its meaning
- List<Task>
- Task list
- new Task { ... }
- New task
- tasks.Add(...)
- Add to list
- tasks.Count
- Task count
Next lesson: Listing tasks