Task model
Design the Task class and its properties.
Project: To-do list
In this 5-lesson project you will build a to-do list application. Each lesson adds one piece; the final lesson gives you a complete command-line application.
The first lesson designs the Task class. A task will have two fields: Title (the title text) and IsDone (whether it is done). This class is used in every lesson of the project, so a solid design matters.
Class and fields
A class groups related data under a single type. It is declared with class Task { ... }. Variables inside a class are called fields; the public keyword allows access from outside.
A new instance of the class is created with new Task(). Fields are accessed with the dot: t.Title. This is similar to the .Length property of arrays.
Exercise Task class and instance
Define the Task class with the fields public string Title; and public bool IsDone;. In Main, create a task with new Task(), assign "Buy bread" to Title and print Title with Console.WriteLine.
Show example solution
Add public string Title; and public bool IsDone; inside Task. In Main write Task t = new Task(); t.Title = "Buy bread"; Console.WriteLine(t.Title);.
Example solution:
using System;
class Task
{
// Declare the Title and IsDone fields
public string Title;
public bool IsDone;
}
class Program
{
static void Main()
{
// Create a Task, set its title and print
Task t = new Task();
t.Title = "Buy bread";
Console.WriteLine(t.Title);
}
}
Test yourself
-
What does the Task instance's Title print?
class Task { public string Title; public bool IsDone; } Task t = new Task(); t.Title = "Buy bread"; Console.WriteLine(t.Title);- Buy bread
- null
- Task
- Empty
Show answer
Buy bread — Correct. After t.Title = "Buy bread", Console.WriteLine prints Buy bread.
-
Declare a class field
class Task { public string Title; public ____ }Show answer
class Task { public string Title; public bool IsDone; } -
Match each expression to its meaning
- public string Title
- Text field
- public bool IsDone
- Boolean field
- new Task()
- New instance
- t.Title
- Field access