Skip to content
Tutorials Center
My learning

Topics

Lesson 170 of 182 ยท Projects

Project: Command-Line To-Do App

Build a command-line to-do app in C# in four stages: records and LINQ, a command parser and menu loop, JSON persistence behind an interface, and a mini test suite with a fake clock.

A to-do list is the classic first project, and for good reason. It is small enough to finish in an afternoon, yet it touches almost every everyday skill: modelling data, reading input, parsing text, saving to disk, and making sure the code keeps working when you change it. If you can build this app cleanly, you can build the same shape of program for any other domain: a contact book, a habit tracker, a shopping list.

In this project you build the app in four stages, and every stage is a complete program that you can run in the editor. In stage 1 you model tasks with a record and query them with LINQ. In stage 2 you add a command parser and a menu loop that reads from the console. In stage 3 you save and load the list as JSON behind an interface, so the storage can be replaced. In stage 4 you add statistics, make "today" injectable with TimeProvider, and write a small test suite that proves the pieces work. The idea throughout is the one professionals use: keep the logic (list, parser) separate from the edges (console, files, clock), and the logic becomes easy to test.

The plan

Here is the design before any code. The parts and the lessons that explain their tools:

Part Job Tools
TodoItem One task, immutable records, enums, nullable value types
TodoList The tasks and the rules for changing them lists, LINQ
CommandParser Turns a line of text into a command object pattern matching, list patterns
TodoApp Runs a command, returns the text to show switch expressions
ITodoStorage Saves and loads tasks JSON, files

The commands are deliberately simple, one line each:

TEXT
add Buy milk !high @2026-11-01     add a task (priority and due date are optional)
list                               show open tasks, most urgent first
list all                           include finished tasks
done 3                             finish task 3
remove 3                           delete task 3
help                               show this list
quit                               leave

Because our editor has no keyboard attached to the program, each example here feeds it a script through the "Program input" box. A real console would echo what you type; our loop prints each line back after a > so the output reads like a session. On your own machine you would run the same code with dotnet run and type the commands yourself.

Stage 1: the model and the list

Start with the data, never with the screen. A task has an id, a title, a priority, an optional due date and a done flag. That is a perfect fit for a record: it is immutable, it compares by value, and with creates a changed copy.

C# Stage 1: TodoItem, TodoList and LINQ queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the choices, because they repeat in every stage:

  • The record is immutable. Complete does not tick a flag on the existing object. It builds a new item with item with { Done = true } and swaps it into the list. Nobody holding an old TodoItem can see it change under their feet, which removes a whole family of bugs.
  • Defaults live in the record. Priority = Priority.Normal and Due = null make the common call short, and the list's Add mirrors them with optional parameters (optional and named arguments).
  • DateOnly? models "maybe no date". A nullable value type says so in the type, so Due ?? DateOnly.MaxValue is the honest way to sort undated tasks last.
  • Queries return copies. All() and Open() return new lists, so a caller cannot reorder or empty the internal list by accident. The cost is one allocation per call, which is irrelevant for a to-do list; for a hot path you would return a read-only view instead.
  • Open() sorts with a chain. OrderByDescending(Priority) puts High first because the enum values are numbered Low = 0, Normal = 1, High = 2. ThenBy breaks ties by due date, then by id, so the order is fully deterministic.
  • Bad input is rejected at the door. ArgumentException.ThrowIfNullOrWhiteSpace guarantees no task has an empty title; code further on never has to check again.

Ask "who is allowed to break this rule?" for every invariant. Here only TodoList can create an item with a fresh id, so ids are unique by construction. If the record's constructor were called freely from outside, you would need to check for duplicates somewhere. The restricted entry point is what makes the guarantee cheap.

Stage 2: commands, a parser and the loop

Now the text interface. The most important decision of this stage is not to put if (line.StartsWith("add")) checks into the loop. Instead the parser turns a line into a command object, and a separate method executes that object. Parsing text is messy, executing a command is logic; keeping them apart means you can test each alone, and you can later feed the same commands from a web page or a button.

The commands form a small closed family, a perfect job for records and a switch expression (pattern matching). Parse failures are not exceptions: typing done banana is normal input, not a bug, so the parser returns an Invalid command carrying a message.

C# Stage 2: parser, executor and a scripted session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This program has a few details worth studying:

  • The loop condition. while (Console.ReadLine() is { } line) reads a line and stops when ReadLine returns null, which is what happens at the end of the input. The is { } pattern means "not null", and it also declares line for the body. Without that null check, a program fed from a file or a pipe would crash or spin forever.
  • rest is ["all"] is a list pattern: it matches an array with exactly one element equal to "all". words is [var text] matches exactly one element and captures it. Both read like the shape of the input (list patterns).
  • words[1..] is a range on an array (ranges and indices); it copies everything after the verb.
  • Enum.TryParse plus Enum.IsDefined. TryParse happily accepts the text "7" and produces (Priority)7, a value that is not one of the names. The extra IsDefined check closes that hole. This is a classic enum pitfall.
  • Primary constructor. TodoApp(TodoList list) captures the list as a parameter that is visible in every method (primary constructors). The class never creates its own TodoList, so a test can give it any list. That is dependency injection in its simplest form (dependency injection).
  • Raw string literal. The HelpText constant is a """ raw string; the indentation of the closing quotes is removed from every line (raw strings).
  • Invalid input is data. Look at the session output: every bad line (add with no title, a bad priority, done banana, an unknown id, an unknown verb) gets a clear one-line message and the loop carries on. Exceptions are for situations the caller cannot reasonably expect; a typo is one it must expect.

The "this line is never read" line at the end of the input shows that quit really stops the loop.

Do not parse with int.Parse in an interactive loop. It throws FormatException for banana, and an app that dies when someone mistypes is a bad app. int.TryParse returns false instead and lets you answer politely.

Stage 3: saving to JSON behind an interface

A to-do list that forgets everything on exit is not much use. For persistence we want two things: a file format that is easy to read and to repair by hand, and a design that does not weld the app to the disk. JSON with System.Text.Json does the first (JSON). A small interface does the second.

C#
public interface ITodoStorage
{
    IReadOnlyList<TodoItem> Load();
    void Save(IEnumerable<TodoItem> items);
}

The app depends on ITodoStorage, never on File. Production uses FileTodoStorage; tests use MemoryTodoStorage with no disk involved. Two details make the file version robust:

  1. Write to a temporary file, then move it over the real one. If the program crashes in the middle of writing, the old file is still intact. A half-written JSON file would otherwise destroy the user's data.
  2. A corrupt file must not be silently replaced by an empty list. If the JSON cannot be read, we say so, and keep going with an empty list only after copying the bad file aside.

The program below also needs TodoList to be restorable: Restore(items) fills the list and sets the next id to one more than the largest id on file, so ids are never reused. The scripted session runs twice. The first "run" adds and finishes tasks and saves automatically after every change. The second "run" builds a brand-new app on the same file and shows that the tasks came back.

C# Stage 3: JSON storage, saved after every change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

There is a lot happening in this stage, so take it in pieces:

  • JsonSerializerDefaults.Web gives camelCase property names (id, title, due), which is the usual JSON style. JsonStringEnumConverter writes "High" instead of 2, so the file is readable and does not break if you reorder the enum.
  • Records deserialize through their constructor. System.Text.Json matches JSON properties to the positional parameters, so TodoItem needs no attributes. DateOnly? is supported natively.
  • The atomic save. File.Move(temp, path, overwrite: true) replaces the target in one step on the same volume. Either the old file or the new file exists, never half of one.
  • Saving after every change is the simplest durable design for a small app: no "unsaved changes" state, and a crash loses nothing. Execute returns a tuple (Message, Changed) so the save happens in exactly one place. Look at how the tuple keeps the decision "did something change?" next to the code that knows.
  • when guards in the switch. DoneCommand done when list.Complete(done.Id) runs the action as a side effect of the guard, which is compact but a little sneaky: the arm only matches if it succeeded, and the later arm DoneCommand or RemoveCommand catches the failures. Use this trick sparingly; a plain if in a method is clearer when the logic grows.
  • A bad file is handled, not hidden. In the third part of the output the damaged file was moved aside to todos.json.bad, the user is told, and the app starts with an empty list. The next save writes a fresh todos.json, and the broken one is still there for repair.

The sandbox lets a program write files in its working directory, but they disappear when the run ends. On your machine todos.json would stay next to your program. In a real app you would store it in a per-user folder such as Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), not in the current directory (files and paths).

Why an interface?

You may wonder whether ITodoStorage is over-engineering for one file. Count the benefits: tests need no disk, you can later swap JSON for SQLite or a web service without touching the app, and the dependency direction is clean (TodoApp knows only the contract). It costs five lines. When there is only ever one implementation and no test needs a fake, skip the interface. Here the tests in stage 4 are the reason.

Stage 4: statistics, a fake clock and tests

The last stage makes the app testable and adds two features that depend on "today": an overdue command and a stats command. Anything that calls DateTime.Now inside your logic is hard to test, because the answer changes every day. The fix is to inject the clock. .NET has a built-in abstraction for this, TimeProvider. Production code uses TimeProvider.System; tests pass their own subclass that always says the same day.

The tests themselves need no framework. A test is a name plus a block of code that throws when something is wrong. About twenty lines give you Test, Equal and a summary. (Real projects use xUnit or NUnit, see xUnit and NUnit; the ideas are identical.)

C# Stage 4: the complete app with a test suite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

What to notice in the finished program:

  • Records give tests equality for free. Equal(new AddCommand("Buy milk", Priority.High, ...), command) compares every property by value, so one line checks the whole parse result. With plain classes you would write a comparison by hand or check each property.
  • The fake clock is five lines. FixedTimeProvider overrides one method. Because TodoApp asks clock.GetUtcNow() and never DateTime.Now, the overdue answer is the same today, tomorrow and on the build server. (The Overdue(DateOnly today) method itself takes a plain date, which makes its test even simpler.)
  • CountBy is a .NET 9 LINQ operator (LINQ operators). CountBy(item => item.Priority) returns key/count pairs in one pass, replacing the older GroupBy(...).Select(g => (g.Key, g.Count())). Priorities with no tasks are missing from the result, which is why Stats uses GetValueOrDefault.
  • The tests found real design points. "ids are not reused" and "restore continues after the largest id" were written because a past bug in similar apps is reusing the id of a deleted task, which silently re-points an old reference to a different task.
  • The test code is the specification. Reading the test names top to bottom tells a new teammate what the app promises.

Where to take it next

Try these extensions; each exercises a different skill, and the structure you built makes every one of them small:

  1. edit <id> <new title> adds a command record, one parser arm and one TodoList method. Use with again.
  2. Tags (#home): parse words starting with # into a string[] property, then add list #home. Think about how an array inside a record affects value equality.
  3. Undo. Keep a stack of previous snapshots (queues and stacks); because items are immutable, a snapshot is just the old list.
  4. A real console prompt with colours and a help screen, in Program.cs only; nothing else in the project should change. If something else must change, a layer is leaking.
  5. Recurring tasks. Add a Repeat field and make Complete create the next occurrence. Write the test first.
  6. Another front end. Reuse TodoList, CommandParser and TodoApp unchanged inside a minimal API; the next-but-one project, the inventory API, shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the parser return an InvalidCommand instead of throwing an exception for the input done banana?

    Users make typos all the time. Exceptions are for unexpected failures; expected bad input is handled with return values so the loop can answer politely and continue.
  2. 2. What is the main reason FileTodoStorage writes to a temporary file and then calls File.Move?

    A direct overwrite can leave a half-written file after a crash or power loss. Writing elsewhere and swapping the finished file in keeps either the old or the new version intact.
  3. 3. Why is TimeProvider passed into TodoApp instead of the code calling DateTime.Now?

    Code that reads the real clock gives different results as days pass. Injecting the clock lets a test freeze time, which makes date-dependent behaviour such as overdue tasks testable.
  4. 4. What does item with { Done = true } do to the original TodoItem record?

    A non-destructive mutation copies every property into a new record and applies the listed changes. The original stays as it was, which is why TodoList replaces the list entry with the new object.
  5. 5. Why does the parser check Enum.IsDefined after Enum.TryParse for the priority?

    Enum.TryParse treats numeric text as a valid value even when no member has that number. IsDefined rejects those values so !7 becomes a clear error.

Summary

  • Build in layers: an immutable model (record), the logic (TodoList), a parser that produces command objects, an executor that returns text, and storage behind an interface.
  • Treat bad user input as data: return an InvalidCommand with a message instead of throwing, and keep the loop alive; stop reading when ReadLine returns null.
  • Persist with System.Text.Json, save after each change, write to a temporary file and move it into place, and never overwrite a damaged file silently.
  • Inject the things that change between runs, such as storage and the clock (TimeProvider), so the logic is deterministic and testable.
  • A test is a name plus code that throws on failure; records make comparing results trivial.
  • Keep the edges (console, files, time) thin and the middle pure, and the app stays easy to change.

Next: Project: Bank Account System