Lesson 22 of 24

In progress

Course progress

C# and .NET

A console app with structure

Lay out a console app with a domain, a service and a file store, and keep the menu free of business rules.

A console app is the smallest complete program: input, logic, output and somewhere to keep the data. Getting the structure right makes it the starting point for a web service later, rather than a script that has to be rewritten.

What you will learn

  • Separate the domain, the service and the interface.
  • Put persistence behind an interface.
  • Keep Program.cs as wiring only.

The layout

Tasks/
Tasks.csproj
Program.cs
Domain/Task.cs
Domain/Priority.cs
Service/TaskService.cs
Storage/ITaskStore.cs
Storage/JsonTaskStore.cs
Cli/Menu.cs

The domain holds the rules, the service coordinates, Storage and Cli are edges. Dependencies point inward: the domain knows nothing about the console or the file system.

The domain

namespace Tasks.Domain;
public enum Priority { Low, Normal, Urgent }
public record Task(int Id, string Title, Priority Priority, bool Done)
{
public Task Complete() => this with { Done = true };
}

with returns a new record, so completing a task does not mutate the old one. That matters when a UI holds the previous value and compares it to detect a change.

The record’s compact constructor could validate the title; here the service does it, because the rule about trimming input belongs with the input handling.

The store

namespace Tasks.Storage;
using Tasks.Domain;
public interface ITaskStore
{
IReadOnlyList<Task> Load();
void Save(IReadOnlyList<Task> tasks);
}
using System.Text.Json;
public class JsonTaskStore : ITaskStore
{
private readonly string path;
public JsonTaskStore(string path) => this.path = path;
public IReadOnlyList<Task> Load()
{
if (!File.Exists(path)) return Array.Empty<Task>();
string json = File.ReadAllText(path);
return JsonSerializer.Deserialize<List<Task>>(json) ?? new List<Task>();
}
public void Save(IReadOnlyList<Task> tasks)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(tasks, new JsonSerializerOptions { WriteIndented = true }));
}
}

System.Text.Json is in the framework, so no package is needed. Enums serialise as numbers by default; add a converter if the file should be readable by a person.

The ! after GetDirectoryName is a promise that the path has a directory. That is true for the paths Program.cs supplies, and it is the kind of narrow use where the null-forgiving operator is honest.

The service

namespace Tasks.Service;
using Tasks.Domain;
using Tasks.Storage;
public class TaskService
{
private readonly ITaskStore store;
private readonly List<Task> tasks;
public TaskService(ITaskStore store)
{
this.store = store;
this.tasks = store.Load().ToList();
}
public Task Add(string title, Priority priority)
{
if (string.IsNullOrWhiteSpace(title))
throw new ArgumentException("title required", nameof(title));
int nextId = tasks.Count == 0 ? 1 : tasks.Max(t => t.Id) + 1;
var task = new Task(nextId, title.Trim(), priority, false);
tasks.Add(task);
store.Save(tasks);
return task;
}
public bool Complete(int id)
{
int index = tasks.FindIndex(t => t.Id == id);
if (index < 0) return false;
tasks[index] = tasks[index].Complete();
store.Save(tasks);
return true;
}
public IReadOnlyList<Task> List(bool onlyOpen) =>
onlyOpen ? tasks.Where(t => !t.Done).ToList() : tasks.AsReadOnly();
}

The service owns the list and saves after every change, so a crash loses at most the action in flight. Complete returns whether it found the task, which lets the menu print an honest message.

List returns a read-only view or a materialised list, so a caller cannot mutate the service’s state through the result.

The menu

namespace Tasks.Cli;
using Tasks.Domain;
using Tasks.Service;
public class Menu
{
private readonly TaskService service;
public Menu(TaskService service) => this.service = service;
public void Run()
{
while (true)
{
Console.Write("[a]dd [l]ist [d]one [q]uit: ");
switch (Console.ReadLine()?.Trim().ToLowerInvariant())
{
case "a": Add(); break;
case "l": List(); break;
case "d": Done(); break;
case "q": return;
default: Console.WriteLine("unknown command"); break;
}
}
}
private void Add()
{
Console.Write("title: ");
string? title = Console.ReadLine();
Console.Write("priority (low/normal/urgent): ");
string? raw = Console.ReadLine();
if (!Enum.TryParse<Priority>(raw, ignoreCase: true, out var priority))
{
Console.WriteLine("invalid priority");
return;
}
try
{
var task = service.Add(title ?? "", priority);
Console.WriteLine($"added #{task.Id}");
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
private void List()
{
var open = service.List(onlyOpen: true);
if (open.Count == 0) { Console.WriteLine("nothing open"); return; }
foreach (var t in open)
Console.WriteLine($"#{t.Id} [{t.Priority}] {t.Title}");
}
private void Done()
{
Console.Write("id: ");
if (int.TryParse(Console.ReadLine(), out int id))
Console.WriteLine(service.Complete(id) ? "completed" : "no such task");
else
Console.WriteLine("enter a number");
}
}

Enum.TryParse handles case and invalid input without an exception. The catch around Add turns the service’s validation into a message, which is the only place a rule becomes text.

Why the split matters

The menu knows how to read a line and print a message; the service knows the rules; the store knows JSON. When a rule changes — say a task cannot be completed twice — only the service changes. When the storage changes, only the store changes. When the interface becomes a web page, only the CLI is replaced.

That is not architecture for its own sake. It is the smallest arrangement in which a change has one place to happen, and it costs four folders and two interfaces. It also makes this console app a rehearsal for the API in the next lesson, because the service does not care who calls it.

Failure paths

A file that cannot be written, a JSON file edited into invalid syntax, a title made only of spaces: each has one owner. The store throws IOException, the service rejects the invalid title, and the menu turns either into a line of text.

Without that split, every one of those failures becomes an unhandled exception in the middle of the display loop, and the user loses the whole session instead of the one action that failed.

Wiring

using Tasks.Cli;
using Tasks.Service;
using Tasks.Storage;
var store = new JsonTaskStore("data/tasks.json");
var service = new TaskService(store);
new Menu(service).Run();

Four lines, and the only place that knows all three layers. Swapping the JSON store for a database means changing one line here, not touching the menu or the rules.

Letting the menu call the store directly. Persistence then happens in two places and one of them will forget to save. The service owns the store; the menu asks the service.

Add a Remove(int id) method to the service and a [r]emove command to the menu, keeping the menu free of storage knowledge.

Show solution
public bool Remove(int id) { int removed = tasks.RemoveAll(t => t.Id == id); if (removed == 0) return false; store.Save(tasks); return true; }

The service decides and persists, and the menu only reads the id and prints a message. RemoveAll returns the count removed, which tells you whether anything happened without a separate search.

Recap

  • Keep the domain free of console and file details, and put persistence behind an interface.
  • Save through the service after every change, and return read-only results.
  • Wire everything in Program.cs so the dependency graph is visible in one place.

Next, a minimal ASP.NET Core API that reuses the same service.

Why JSON rather than CSV?
JSON round-trips nested data and needs no parser. `System.Text.Json` is already in the framework.
Where does the data file live?
Relative to the working directory, so use an absolute path from `AppContext.BaseDirectory` for anything shipped.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.