Now change the program yourself. A new command touches several files, and you'll find the layers tell you where each piece belongs: a rule goes in Tracker, text goes in Commands.
A warm-up on with
Rescheduling replaces a value inside a record, exactly as Complete does. A record's copies are independent, and comparing them shows what changed. Predict this.
A changed copyC#
var task = new Item(1, new DateOnly(2026, 11, 2));
Item moved = task with { Due = task.Due.AddDays(7) };
Console.WriteLine(task.Due.ToString("yyyy-MM-dd"));
Console.WriteLine(moved.Due.ToString("yyyy-MM-dd"));
Console.WriteLine(task == moved);
Console.WriteLine(task == moved with { Due = task.Due });
record Item(int Id, DateOnly Due);
Check your prediction
Text
2026-11-022026-11-09FalseTrue
Your turn
Exercise
Add a reschedule command
In the tabs below, add a command move <id> <yyyy-MM-dd>, which changes a task's due date and prints Moved 1 to 2026-11-09. An unknown id prints Error: no task 9, and a bad date prints Error: bad date .... A finished task can't be moved: print Error: task 1 is finished. Add lines to the input box to try each case.
When it works, it prints:
Text
Moved 1 to 2026-11-09Error: no task 9Error: bad date soonError: task 2 is finishedError: usage: move <id> <yyyy-MM-dd>
Your workspaceC##nullable enable
using TaskTracker;
var commands = new Commands(new Tracker(), new SystemClock());
string? line;
while ((line = Console.ReadLine()) is not null)
{
foreach (string output in commands.Execute(line))
{
Console.WriteLine(output);
}
}
#nullable enable
using System.Globalization;
namespace TaskTracker;
// Turns one line of text into output lines, so it can be checked without a console.
public class Commands
{
private readonly Tracker tracker;
private IClock clock;
public Commands(Tracker tracker, IClock clock)
{
this.tracker = tracker;
this.clock = clock;
}
public IReadOnlyList<string> Execute(string line)
{
string[] parts = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 0)
{
return Array.Empty<string>();
}
string argument = parts.Length == 2 ? parts[1] : "";
return parts[0] switch
{
"add" => Add(argument),
"done" => WithId(argument, "Completed", tracker.Complete),
"remove" => WithId(argument, "Removed", tracker.Remove),
"list" => List(),
"report" => BuildReport(),
"save" => Store(argument, tracker.Save, "Saved"),
"load" => Store(argument, tracker.Load, "Loaded"),
"today" => SetToday(argument),
_ => Error($"unknown command {parts[0]}"),
};
}
private static string[] Error(string message) => new[] { $"Error: {message}" };
private static bool TryParseDate(string text, out DateOnly date)
{
return DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
private string[] Add(string argument)
{
string[] fields = argument.Split(' ', 3, StringSplitOptions.TrimEntries);
if (fields.Length != 3)
{
return Error("usage: add <priority> <yyyy-MM-dd> <title>");
}
if (!Enum.TryParse(fields[0], ignoreCase: true, out Priority priority) || !Enum.IsDefined(priority))
{
return Error($"unknown priority {fields[0]}");
}
if (!TryParseDate(fields[1], out DateOnly due))
{
return Error($"bad date {fields[1]}");
}
return tracker.Add(fields[2], priority, due) switch
{
Ok<TaskItem> ok => new[] { $"Added {ok.Value.Id}: {ok.Value.Title}" },
Fail<TaskItem> fail => Error(fail.Error),
_ => throw new InvalidOperationException("unknown result"),
};
}
private static string[] WithId(string argument, string verb, Func<int, Result<TaskItem>> action)
{
if (!int.TryParse(argument, out int id))
{
return Error($"bad id {argument}");
}
return action(id) switch
{
Ok<TaskItem> ok => new[] { $"{verb} {ok.Value.Id}: {ok.Value.Title}" },
Fail<TaskItem> fail => Error(fail.Error),
_ => throw new InvalidOperationException("unknown result"),
};
}
private string[] List()
{
return Reports.Ordered(tracker.Tasks)
.Select(task => $"[{(task.Done ? "x" : " ")}] {task.Id} {task.Priority} {task.Due:yyyy-MM-dd} {task.Title}")
.ToArray();
}
private string[] BuildReport()
{
Report report = Reports.Build(tracker.Tasks.ToList(), clock.Today);
var lines = new List<string>
{
$"Open: {report.Open}",
$"Done: {report.Done}",
$"Overdue: {report.Overdue}",
};
foreach (Priority priority in Enum.GetValues<Priority>().Reverse())
{
report.OpenByPriority.TryGetValue(priority, out int count);
lines.Add($"{priority}: {count}");
}
return lines.ToArray();
}
private static string[] Store(string path, Func<ITaskStore, Result<int>> action, string verb)
{
if (path.Length == 0)
{
return Error("a file name is required");
}
return action(new JsonFileStore(path)) switch
{
Ok<int> ok => new[] { $"{verb} {ok.Value} tasks" },
Fail<int> fail => Error(fail.Error),
_ => throw new InvalidOperationException("unknown result"),
};
}
private string[] SetToday(string argument)
{
if (!TryParseDate(argument, out DateOnly today))
{
return Error($"bad date {argument}");
}
clock = new FixedClock(today);
return new[] { $"Today is {today:yyyy-MM-dd}" };
}
}
#nullable enable
namespace TaskTracker;
public class Tracker
{
public const int MaxTitleLength = 60;
private readonly List<TaskItem> tasks = new();
private int nextId = 1;
public IReadOnlyList<TaskItem> Tasks => tasks;
public Result<TaskItem> Add(string title, Priority priority, DateOnly due)
{
string trimmed = title.Trim();
if (trimmed.Length == 0 || trimmed.Length > MaxTitleLength)
{
return new Fail<TaskItem>($"title must be 1 to {MaxTitleLength} characters");
}
var task = new TaskItem(nextId, trimmed, priority, due);
nextId++;
tasks.Add(task);
return new Ok<TaskItem>(task);
}
public Result<TaskItem> Complete(int id)
{
int index = tasks.FindIndex(task => task.Id == id);
if (index < 0)
{
return new Fail<TaskItem>($"no task {id}");
}
tasks[index] = tasks[index] with { Done = true };
return new Ok<TaskItem>(tasks[index]);
}
public Result<TaskItem> Remove(int id)
{
int index = tasks.FindIndex(task => task.Id == id);
if (index < 0)
{
return new Fail<TaskItem>($"no task {id}");
}
TaskItem removed = tasks[index];
tasks.RemoveAt(index);
return new Ok<TaskItem>(removed);
}
public Result<int> Save(ITaskStore store)
{
try
{
store.Save(tasks);
return new Ok<int>(tasks.Count);
}
catch (IOException e)
{
return new Fail<int>(e.Message);
}
}
// Replaces the tasks only after everything loaded and validated.
public Result<int> Load(ITaskStore store)
{
IReadOnlyList<TaskItem> loaded;
try
{
loaded = store.Load();
}
catch (IOException e)
{
return new Fail<int>(e.Message);
}
catch (StoreFormatException e)
{
return new Fail<int>(e.Message);
}
// Nullable annotations are not enforced when JSON is read, so a list can hold null.
if (loaded.Any(task => task is null))
{
return new Fail<int>("saved data has an empty entry");
}
if (loaded.Any(task => task.Title is null || task.Title.Trim().Length == 0 || task.Title.Length > MaxTitleLength))
{
return new Fail<int>("saved data has an invalid title");
}
// An enum accepts any number of its underlying type, such as 99 in a saved file.
if (loaded.Any(task => !Enum.IsDefined(task.Priority)))
{
return new Fail<int>("saved data has an invalid priority");
}
if (loaded.Select(task => task.Id).Distinct().Count() != loaded.Count || loaded.Any(task => task.Id < 1))
{
return new Fail<int>("saved data has invalid ids");
}
tasks.Clear();
tasks.AddRange(loaded);
nextId = tasks.Count == 0 ? 1 : tasks.Max(task => task.Id) + 1;
return new Ok<int>(tasks.Count);
}
}
#nullable enable
namespace TaskTracker;
public enum Priority { Low, Normal, High }
public record TaskItem(int Id, string Title, Priority Priority, DateOnly Due, bool Done = false);
// A result is exactly one of two cases, so a caller has to look before using a value.
public abstract record Result<T>;
public sealed record Ok<T>(T Value) : Result<T>;
public sealed record Fail<T>(string Error) : Result<T>;
#nullable enable
using System.Text.Json;
using System.Text.Json.Serialization;
namespace TaskTracker;
public interface ITaskStore
{
IReadOnlyList<TaskItem> Load();
void Save(IEnumerable<TaskItem> tasks);
}
public class StoreFormatException : Exception
{
public StoreFormatException(string message, Exception? inner = null) : base(message, inner) { }
}
public class JsonFileStore : ITaskStore
{
private static readonly JsonSerializerOptions Options = new()
{
WriteIndented = true,
Converters = { new JsonStringEnumConverter() },
};
private readonly string path;
public JsonFileStore(string path)
{
this.path = path;
}
public IReadOnlyList<TaskItem> Load()
{
string json = File.ReadAllText(path);
List<TaskItem>? loaded;
try
{
loaded = JsonSerializer.Deserialize<List<TaskItem>>(json, Options);
}
catch (JsonException e)
{
throw new StoreFormatException($"{path} is not valid task data", e);
}
// The text "null" is valid JSON but not a task list; an empty list is written [].
return loaded ?? throw new StoreFormatException($"{path} is not valid task data");
}
// Write to a temporary file first, so a failed write can't damage the last good save.
public void Save(IEnumerable<TaskItem> tasks)
{
string temporary = path + ".tmp";
File.WriteAllText(temporary, JsonSerializer.Serialize(tasks, Options));
File.Move(temporary, path, overwrite: true);
}
}
#nullable enable
namespace TaskTracker;
public record Report(int Open, int Done, int Overdue, IReadOnlyDictionary<Priority, int> OpenByPriority);
public static class Reports
{
// Open tasks first, then soonest due, then highest priority; the id keeps ties stable.
public static IEnumerable<TaskItem> Ordered(IEnumerable<TaskItem> tasks)
{
return tasks
.OrderBy(task => task.Done)
.ThenBy(task => task.Due)
.ThenByDescending(task => task.Priority)
.ThenBy(task => task.Id);
}
public static IEnumerable<TaskItem> Overdue(IEnumerable<TaskItem> tasks, DateOnly today)
{
return tasks.Where(task => !task.Done && task.Due < today);
}
public static Report Build(IReadOnlyCollection<TaskItem> tasks, DateOnly today)
{
var open = tasks.Where(task => !task.Done).ToList();
var byPriority = open.GroupBy(task => task.Priority).ToDictionary(group => group.Key, group => group.Count());
return new Report(open.Count, tasks.Count - open.Count, Overdue(tasks, today).Count(), byPriority);
}
}
#nullable enable
namespace TaskTracker;
public interface IClock
{
DateOnly Today { get; }
}
public class SystemClock : IClock
{
public DateOnly Today => DateOnly.FromDateTime(DateTime.Now);
}
public class FixedClock : IClock
{
public DateOnly Today { get; }
public FixedClock(DateOnly today)
{
Today = today;
}
}
today 2026-11-02
add High 2026-11-01 Write report
add Low 2026-11-20 Read chapter
add Normal 2026-11-05 Review notes
add Urgent 2026-11-05 Bad priority
done 2
done 9
list
report
save tasks.json
remove 3
list
load tasks.json
list
Hint 1: the idea
The rule goes in a new Tracker.Move(int id, DateOnly due) method, returning Result<TaskItem>, shaped much like Complete. Parsing belongs in Commands, which already has TryParseDate.
Hint 2: a first step
Add "move" => Move(argument), to the switch in Execute, and have your new method return Error("not yet"). Then fill in the split, the parsing, and the call.
Show one solution
The changed parts are shown together here, so that this listing can run by itself.
C#
#nullable enableusing System.Globalization;var tracker = new Tracker();tracker.Add("Read", new DateOnly(2026, 11, 2));tracker.Add("Write", new DateOnly(2026, 11, 3));tracker.Complete(2);foreach (string argument in new[] { "1 2026-11-09", "9 2026-11-09", "1 soon", "2 2026-11-09", "1" }){ Console.WriteLine(Move(tracker, argument));}static string Move(Tracker tracker, string argument){ string[] fields = argument.Split(' '); if (fields.Length != 2 || !int.TryParse(fields[0], out int id)) { return "Error: usage: move <id> <yyyy-MM-dd>"; } if (!DateOnly.TryParseExact(fields[1], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly due)) { return $"Error: bad date {fields[1]}"; } return tracker.Move(id, due) switch { Ok<TaskItem> ok => $"Moved {ok.Value.Id} to {ok.Value.Due:yyyy-MM-dd}", Fail<TaskItem> fail => $"Error: {fail.Error}", _ => throw new InvalidOperationException("unknown result"), };}class Tracker{ private readonly List<TaskItem> tasks = new(); private int nextId = 1; public void Add(string title, DateOnly due) { tasks.Add(new TaskItem(nextId++, title, due)); } public void Complete(int id) { int index = tasks.FindIndex(task => task.Id == id); tasks[index] = tasks[index] with { Done = true }; } public Result<TaskItem> Move(int id, DateOnly due) { int index = tasks.FindIndex(task => task.Id == id); if (index < 0) { return new Fail<TaskItem>($"no task {id}"); } if (tasks[index].Done) { return new Fail<TaskItem>($"task {id} is finished"); } tasks[index] = tasks[index] with { Due = due }; return new Ok<TaskItem>(tasks[index]); }}record TaskItem(int Id, string Title, DateOnly Due, bool Done = false);abstract record Result<T>;sealed record Ok<T>(T Value) : Result<T>;sealed record Fail<T>(string Error) : Result<T>;
Text
Moved 1 to 2026-11-09Error: no task 9Error: bad date soonError: task 2 is finishedError: usage: move <id> <yyyy-MM-dd>
The work is split the way the tracker splits it. Move the command checks the text (two fields, a number, a valid date) and Tracker.Move checks the state (the task exists and isn't finished). Each returns the first problem it finds, so every bad input gets one precise message. TryParseExact with InvariantCulture accepts only yyyy-MM-dd, whatever the computer's settings.
Add checks for your command as well: the unknown id, the finished task and a successful move. More ideas: a find <word> command with LINQ, a clear command that removes finished tasks, or a tag field, which forces you to think about old saved files that don't have one.
Optional local setup
Everything so far has run in your browser, and you can stop here. To work on your computer, download the C# task tracker. It holds the same source files as the tabs, along with a project file, sample input and a README. Your browser edits aren't included.
Install the .NET 10 SDK from dotnet.microsoft.com, open a terminal in the extracted folder, and run:
Shell
dotnet --versiondotnet run < sample-input.txtdotnet run --property:Checks=true
In Windows PowerShell, use Get-Content sample-input.txt | dotnet run in place of the second line. After a local run, tasks.json stays in the folder, so you can open it, read it and damage it, then see what load says.
Larger projects put tests in a separate project with a framework such as xUnit, using dotnet test. This project's Checks switch keeps both in one folder, so the same files work here and in the browser.
Completion is saved in this browser only. It does not measure mastery.