Tutorials / C# for Beginners / Expense tracker, part 1: planning, model and storage

Expense tracker, part 1: planning, model and storage

15 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. 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.

  1. The model. One Expense class that describes a single spending record.
  2. The storage. An ExpenseStore class that loads and saves the list. It knows about files and JSON, and nothing about the console.
  3. The menu. The code in Program.cs that 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

  1. Create a new project with dotnet new console -n ExpenseTracker and paste in the code. Run it twice and check that the output is the same each time.
  2. Open the JSON file in your editor and look at its shape.
  3. Add a method TotalFor(string category) to the store that returns the sum of that category's amounts.
csharp
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