Expense tracker, part 1: planning, model and storage
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
What we are building
For the last two lessons we build a real tool: a console expense tracker. You will be able to add an expense, list all expenses, see totals per category, and delete an entry. The data is saved to a JSON file, so it is still there tomorrow.
Before typing code, I always write down the parts. Beginners skip this step and get lost halfway. Our program has three parts.
- The model. One
Expenseclass that describes a single spending record. - The storage. An
ExpenseStoreclass that loads and saves the list. It knows about files and JSON, and nothing about the console. - The menu. The code in
Program.csthat talks to the user. It calls the store and prints results.
This split is the main lesson of the project. When each part has one job, you can change one without breaking the others. If you later want to store data in a database instead of a file, only the storage part changes.
The model
An expense needs an id so we can delete it, a date, a description, a category and an amount. We use decimal for the amount, as the types lesson explained. I use properties with init, because an expense does not change after it is created.
The storage class
The store keeps the expenses in a List<Expense> and writes the list to a file after each change. It also hands out new ids. Here is a complete, runnable version with a short test at the top. It adds two expenses, saves them, loads them again into a second store, and prints what it finds.
using System.Text.Json;
string path = Path.Combine(AppContext.BaseDirectory, "expenses-test.json");
if (File.Exists(path)) File.Delete(path);
var store = new ExpenseStore(path);
store.Add(new DateOnly(2026, 3, 2), "Groceries", "Food", 4250.50m);
store.Add(new DateOnly(2026, 3, 3), "Bus pass", "Transport", 1800m);
Console.WriteLine($"Saved {store.All.Count} expenses to {path}");
// A second store reading the same file proves the data survived
var reloaded = new ExpenseStore(path);
foreach (Expense e in reloaded.All)
{
Console.WriteLine($"#{e.Id} {e.Date:yyyy-MM-dd} {e.Category,-10} {e.Amount,10:N2} {e.Description}");
}
class Expense
{
public int Id { get; init; }
public DateOnly Date { get; init; }
public string Description { get; init; } = "";
public string Category { get; init; } = "";
public decimal Amount { get; init; }
}
class ExpenseStore
{
private readonly string _path;
private readonly List<Expense> _items = new();
private static readonly JsonSerializerOptions Options = new() { WriteIndented = true };
public ExpenseStore(string path)
{
_path = path;
Load();
}
public IReadOnlyList<Expense> All => _items;
public Expense Add(DateOnly date, string description, string category, decimal amount)
{
int nextId = _items.Count == 0 ? 1 : _items.Max(e => e.Id) + 1;
var expense = new Expense
{
Id = nextId,
Date = date,
Description = description,
Category = category,
Amount = amount
};
_items.Add(expense);
Save();
return expense;
}
public bool Remove(int id)
{
int removed = _items.RemoveAll(e => e.Id == id);
if (removed == 0) return false;
Save();
return true;
}
private void Load()
{
if (!File.Exists(_path)) return;
try
{
string json = File.ReadAllText(_path);
var loaded = JsonSerializer.Deserialize<List<Expense>>(json);
if (loaded != null) _items.AddRange(loaded);
}
catch (JsonException)
{
Console.Error.WriteLine("The data file is damaged. Starting with an empty list.");
}
}
private void Save()
{
File.WriteAllText(_path, JsonSerializer.Serialize(_items, Options));
}
}
Walking through it
The test at the top creates a store pointing to a temporary file, adds two expenses and prints the count. Then it creates a second ExpenseStore for the same path. Its constructor calls Load, so it reads what the first one saved. Seeing both rows printed proves the round trip works. I always test the storage on its own like this. If saving is broken, I want to know before I have a menu on top of it.
In ExpenseStore, the list is private and the public All property exposes it as read-only. Outside code cannot add to the list directly, so every change goes through Add or Remove, and every change is saved. That is encapsulation from the classes lesson, doing a real job.
The next id is the highest existing id plus one. Using Count + 1 would be a bug. If you delete expense 2 out of 3, the count is 2 and the next id would be 3, which already exists.
The Load method returns quietly if the file does not exist, which is the normal first run. It catches JsonException for a damaged file, writes a message to the error stream and carries on with an empty list. The Save method serialises the whole list. For a few thousand records this is fast enough. A larger application would use a database.
The DateOnly type holds a date with no time, which is right for an expense. The format {e.Category,-10} pads the category to ten characters, left-aligned, so the columns line up.
Common mistakes
- Mixing console code into the store. A class that both reads files and prints to the screen is hard to reuse.
- Using the count as the next id. It repeats ids after a delete.
- Forgetting to save after a change. The program works until it is closed, and then the data is gone.
- Storing money as double.
Try it yourself
- Create a new project with
dotnet new console -n ExpenseTrackerand paste in the code. Run it twice and check that the output is the same each time. - Open the JSON file in your editor and look at its shape.
- Add a method
TotalFor(string category)to the store that returns the sum of that category's amounts.
using System.Text.Json;
string path = Path.Combine(AppContext.BaseDirectory, "expenses-test.json");
if (File.Exists(path)) File.Delete(path);
var store = new ExpenseStore(path);
store.Add(new DateOnly(2026, 3, 2), "Groceries", "Food", 4250.50m);
store.Add(new DateOnly(2026, 3, 3), "Bus pass", "Transport", 1800m);
Console.WriteLine($"Saved {store.All.Count} expenses to {path}");
// A second store reading the same file proves the data survived
var reloaded = new ExpenseStore(path);
foreach (Expense e in reloaded.All)
{
Console.WriteLine($"#{e.Id} {e.Date:yyyy-MM-dd} {e.Category,-10} {e.Amount,10:N2} {e.Description}");
}
class Expense
{
public int Id { get; init; }
public DateOnly Date { get; init; }
public string Description { get; init; } = "";
public string Category { get; init; } = "";
public decimal Amount { get; init; }
}
class ExpenseStore
{
private readonly string _path;
private readonly List<Expense> _items = new();
private static readonly JsonSerializerOptions Options = new() { WriteIndented = true };
public ExpenseStore(string path)
{
_path = path;
Load();
}
public IReadOnlyList<Expense> All => _items;
public Expense Add(DateOnly date, string description, string category, decimal amount)
{
int nextId = _items.Count == 0 ? 1 : _items.Max(e => e.Id) + 1;
var expense = new Expense
{
Id = nextId,
Date = date,
Description = description,
Category = category,
Amount = amount
};
_items.Add(expense);
Save();
return expense;
}
public bool Remove(int id)
{
int removed = _items.RemoveAll(e => e.Id == id);
if (removed == 0) return false;
Save();
return true;
}
private void Load()
{
if (!File.Exists(_path)) return;
try
{
string json = File.ReadAllText(_path);
var loaded = JsonSerializer.Deserialize<List<Expense>>(json);
if (loaded != null) _items.AddRange(loaded);
}
catch (JsonException)
{
Console.Error.WriteLine("The data file is damaged. Starting with an empty list.");
}
}
private void Save()
{
File.WriteAllText(_path, JsonSerializer.Serialize(_items, Options));
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account