← العودة إلى الدورة: C# from scratch

Final project: console expense tracker with JSON

الفيديو قريبًا

The time has come to put together everything you learned in a complete program. The final project is a personal expense tracker in the console: the person registers expenses with a date, category, description and amount, lists them, filters them, sees summaries by category and by month, deletes the ones entered by mistake, and everything is saved in a JSON file so it is still there the next day. It is a realistic and yet small project: it fits in about 200 well-organized lines of code, and it uses variables, decisions, loops, collections, methods, classes, records, exceptions, LINQ and JSON.

Requirements

  • Create the project with dotnet new console and nullability enabled.
  • A record Expense(int Id, DateOnly Date, string Category, string Description, decimal Amount).
  • A looping menu: 1) add expense, 2) list expenses, 3) summary by category, 4) total by month, 5) delete by Id, 0) exit.
  • Validate all input with TryParse and clear messages; the amount must be greater than 0 and the category cannot be empty.
  • Save the expenses in expenses.json and load them at startup; if the file does not exist or is damaged, start with an empty list without the program failing.
  • Use LINQ for the summaries and a separate class (ExpenseStore) that encapsulates the list and the file.

Starting point: the data store

Start with the part that has no interface: the model and the store. We give you a base that already works; your job is to complete it and build the menu. Notice how ExpenseStore hides the list (private), exposes only methods with rules and saves the file every time something changes. Also notice that Load catches the expected errors and never lets the program crash because of a damaged file.

csharp
using System.Text.Json;

string path = Path.Combine(Path.GetTempPath(), "expenses-demo.json");
File.Delete(path);                         // start from a clean file for this demo
var store = new ExpenseStore(path);
store.Add(new DateOnly(2025, 3, 10), "Food", "Lunch", 12.5m);
store.Add(new DateOnly(2025, 3, 12), "Transport", "Bus pass", 40m);
store.Add(new DateOnly(2025, 4, 2), "Food", "Groceries", 87.25m);

foreach (var row in store.TotalsByCategory())
{
    Console.WriteLine($"{row.Key,-10} {row.Value,8:0.00}");
}
// Food          99.75
// Transport     40.00

Console.WriteLine(store.Delete(2));        // True
Console.WriteLine(store.Delete(99));       // False
Console.WriteLine(store.All.Count);        // 2

record Expense(int Id, DateOnly Date, string Category, string Description, decimal Amount);

class ExpenseStore
{
    private readonly string _path;
    private readonly List<Expense> _items;
    private static readonly JsonSerializerOptions Options = new() { WriteIndented = true };

    public ExpenseStore(string path)
    {
        _path = path;
        _items = Load(path);
    }

    public IReadOnlyList<Expense> All => _items;

    public Expense Add(DateOnly date, string category, string description, decimal amount)
    {
        if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        if (string.IsNullOrWhiteSpace(category)) throw new ArgumentException("Category is required");

        int id = _items.Count == 0 ? 1 : _items.Max(e => e.Id) + 1;
        var expense = new Expense(id, date, category.Trim(), description.Trim(), amount);
        _items.Add(expense);
        Save();
        return expense;
    }

    public bool Delete(int id)
    {
        int removed = _items.RemoveAll(e => e.Id == id);
        if (removed > 0) Save();
        return removed > 0;
    }

    public IEnumerable<KeyValuePair<string, decimal>> TotalsByCategory() =>
        _items.GroupBy(e => e.Category)
              .ToDictionary(g => g.Key, g => g.Sum(e => e.Amount))
              .OrderByDescending(p => p.Value);

    private void Save() => File.WriteAllText(_path, JsonSerializer.Serialize(_items, Options));

    private static List<Expense> Load(string path)
    {
        try
        {
            if (!File.Exists(path)) return [];
            string json = File.ReadAllText(path);
            return JsonSerializer.Deserialize<List<Expense>>(json) ?? [];
        }
        catch (Exception ex) when (ex is JsonException or IOException)
        {
            Console.WriteLine($"Could not read the file ({ex.Message}). Starting empty.");
            return [];
        }
    }
}

Suggested steps

  • Step 1: create the project and copy the model and the store; run it and check that the JSON is created and reloaded when you run it again.
  • Step 2: add the method that returns the total by month (GroupBy on Date.Year and Date.Month) and a filter by category with Where.
  • Step 3: write helper methods ReadDecimal, ReadDate and ReadText that repeat the question until the input is valid (do-while + TryParse; for dates use DateOnly.TryParse).
  • Step 4: build the menu with a while loop and a switch; each option calls a small, clearly named method.
  • Step 5: catch ArgumentException and show its message instead of letting the program crash.
  • Step 6: test the extreme cases: empty list, zero or negative amount, text instead of numbers, JSON file deleted or full of garbage.
csharp
// Skeleton of the menu loop (add your own helper methods)
bool running = true;
while (running)
{
    Console.WriteLine();
    Console.WriteLine("1) Add  2) List  3) By category  4) By month  5) Delete  0) Exit");
    Console.Write("Choose: ");
    string choice = Console.ReadLine() ?? "0";

    switch (choice)
    {
        case "1": Console.WriteLine("-> add an expense here"); break;
        case "2": Console.WriteLine("-> list expenses here"); break;
        case "3": Console.WriteLine("-> category summary here"); break;
        case "4": Console.WriteLine("-> monthly totals here"); break;
        case "5": Console.WriteLine("-> delete here"); break;
        case "0": running = false; break;
        default: Console.WriteLine("Invalid option"); break;
    }
}
Console.WriteLine("Bye!");

Completion criteria

  • The program compiles with no errors or nullability warnings and does not crash with invalid input.
  • All the menu options work and the data persists between runs.
  • The summaries by category and by month are correct (check them by hand with three or four expenses).
  • The data logic is in the ExpenseStore class and the menu only asks for data and shows results.
  • Names of methods, variables and classes are clear and the code reads from top to bottom without unnecessary comments.

اختبر ما تعلمته

السؤال 1 من 6

What does ExpenseStore do with the list of expenses?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابق