Expense tracker, part 2: the menu and summaries
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
Adding the user interface
The store from the last lesson does the real work. Now we write the console part: a menu that loops until the user quits, input helper methods that refuse bad data, and report methods that print a list and a summary. Everything you have learned appears here: loops, switch, methods, parsing, lists, classes, files and exception handling.
Copy the complete program below into a new project's Program.cs. The Expense and ExpenseStore classes are the same ones from part 1. The listing below leaves them out to save space. Paste them at the bottom of the same file, below this code, or keep them in their own files.
using System.Text.Json;
string dataFile = Path.Combine(AppContext.BaseDirectory, "expenses.json");
var store = new ExpenseStore(dataFile);
Console.WriteLine("Expense Tracker");
Console.WriteLine("===============");
bool running = true;
while (running)
{
Console.WriteLine();
Console.WriteLine("1) Add expense");
Console.WriteLine("2) List expenses");
Console.WriteLine("3) Totals by category");
Console.WriteLine("4) Delete expense");
Console.WriteLine("5) Quit");
Console.Write("Choose an option: ");
switch (Console.ReadLine()?.Trim())
{
case "1": AddExpense(store); break;
case "2": ListExpenses(store); break;
case "3": ShowTotals(store); break;
case "4": DeleteExpense(store); break;
case "5": running = false; break;
default: Console.WriteLine("Please choose a number from 1 to 5."); break;
}
}
Console.WriteLine("Goodbye.");
static void AddExpense(ExpenseStore store)
{
DateOnly date = ReadDate("Date (yyyy-mm-dd, blank for today): ");
string description = ReadText("Description: ");
string category = ReadText("Category: ");
decimal amount = ReadAmount("Amount: ");
Expense added = store.Add(date, description, category, amount);
Console.WriteLine($"Saved expense #{added.Id}.");
}
static void ListExpenses(ExpenseStore store)
{
if (store.All.Count == 0)
{
Console.WriteLine("No expenses yet.");
return;
}
Console.WriteLine($"{"Id",3} {"Date",-10} {"Category",-12} {"Amount",10} Description");
foreach (Expense e in store.All.OrderBy(e => e.Date))
{
Console.WriteLine($"{e.Id,3} {e.Date:yyyy-MM-dd} {e.Category,-12} {e.Amount,10:N2} {e.Description}");
}
Console.WriteLine($"Total: {store.All.Sum(e => e.Amount):N2}");
}
static void ShowTotals(ExpenseStore store)
{
if (store.All.Count == 0)
{
Console.WriteLine("No expenses yet.");
return;
}
decimal grand = store.All.Sum(e => e.Amount);
var groups = store.All
.GroupBy(e => e.Category, StringComparer.OrdinalIgnoreCase)
.Select(g => new { Category = g.Key, Total = g.Sum(e => e.Amount), Count = g.Count() })
.OrderByDescending(x => x.Total);
foreach (var g in groups)
{
decimal percent = g.Total / grand * 100;
Console.WriteLine($"{g.Category,-12} {g.Total,10:N2} {percent,5:F1}% ({g.Count} items)");
}
}
static void DeleteExpense(ExpenseStore store)
{
ListExpenses(store);
if (store.All.Count == 0) return;
Console.Write("Id to delete: ");
if (int.TryParse(Console.ReadLine(), out int id) && store.Remove(id))
{
Console.WriteLine("Deleted.");
}
else
{
Console.WriteLine("No expense with that id.");
}
}
static string ReadText(string prompt)
{
while (true)
{
Console.Write(prompt);
string text = (Console.ReadLine() ?? "").Trim();
if (text.Length > 0) return text;
Console.WriteLine("This cannot be empty.");
}
}
static decimal ReadAmount(string prompt)
{
while (true)
{
Console.Write(prompt);
if (decimal.TryParse(Console.ReadLine(), out decimal amount) && amount > 0)
{
return amount;
}
Console.WriteLine("Enter a positive number, for example 450.75.");
}
}
static DateOnly ReadDate(string prompt)
{
while (true)
{
Console.Write(prompt);
string text = (Console.ReadLine() ?? "").Trim();
if (text.Length == 0) return DateOnly.FromDateTime(DateTime.Today);
if (DateOnly.TryParse(text, out DateOnly date)) return date;
Console.WriteLine("Use the format yyyy-mm-dd, for example 2026-03-15.");
}
}
Walking through it
The top of the file is short on purpose. It creates the store and runs a loop. Each pass prints the menu, reads a choice and uses a switch statement to call one method. The variable running controls the loop, and option 5 sets it to false. I use Console.ReadLine()?.Trim() so a null from the console does not crash anything. A null just falls through to the default case.
The three Read... methods are the input layer. Each one loops until the user gives something valid, then returns it. Because they are separate methods, AddExpense stays short and readable, and the validation rules live in one place each. Compare this with the pasted-everywhere input code you might have written a month ago.
The summary method uses LINQ. GroupBy collects expenses by category. I pass StringComparer.OrdinalIgnoreCase so "Food" and "food" end up in one group. Select builds a small anonymous object with the total and the count for each group, and OrderByDescending puts the biggest spending first. LINQ is a large topic. For now it is enough to read the chain top to bottom as a description of what you want.
In the list method, $"{"Id",3}" uses a quoted string inside an interpolation hole. This is allowed and gives the header the same widths as the rows.
Testing the program
Run it and try to break it. Add an expense with an empty description. Type letters for the amount. Enter a date like 2026-13-45. Delete an id that does not exist. Quit and restart to confirm that your expenses are still there. Open expenses.json in the bin output folder and read it. Each of these tests matches a feature we built on purpose.
Where to go next
- Add an option to edit an expense.
- Filter the list by month, or by category.
- Add a monthly budget per category and warn when it is exceeded.
- Export the list as a CSV file.
- Move the classes into their own files, and then write a few tests for
ExpenseStore.
Common mistakes
- Letting the menu code grow into the storage class. Keep the layers apart.
- Trusting what the user types. Every input goes through a validating helper.
- Not handling an empty list. Summaries on no data should say so, not crash.
Try it yourself
- Add menu option 6, "Total for a month", which asks for a year and month and prints the sum.
- Show the five largest expenses using
OrderByDescendingandTake(5). - Write down, in your own words, what each of the three parts of the program is responsible for. If you can do that, you understand the design.
You have now written a complete program with C#. The advanced course continues from here with records, generics, LINQ in depth, async code and ASP.NET Core.
using System.Text.Json;
string dataFile = Path.Combine(AppContext.BaseDirectory, "expenses.json");
var store = new ExpenseStore(dataFile);
Console.WriteLine("Expense Tracker");
Console.WriteLine("===============");
bool running = true;
while (running)
{
Console.WriteLine();
Console.WriteLine("1) Add expense");
Console.WriteLine("2) List expenses");
Console.WriteLine("3) Totals by category");
Console.WriteLine("4) Delete expense");
Console.WriteLine("5) Quit");
Console.Write("Choose an option: ");
switch (Console.ReadLine()?.Trim())
{
case "1": AddExpense(store); break;
case "2": ListExpenses(store); break;
case "3": ShowTotals(store); break;
case "4": DeleteExpense(store); break;
case "5": running = false; break;
default: Console.WriteLine("Please choose a number from 1 to 5."); break;
}
}
Console.WriteLine("Goodbye.");
static void AddExpense(ExpenseStore store)
{
DateOnly date = ReadDate("Date (yyyy-mm-dd, blank for today): ");
string description = ReadText("Description: ");
string category = ReadText("Category: ");
decimal amount = ReadAmount("Amount: ");
Expense added = store.Add(date, description, category, amount);
Console.WriteLine($"Saved expense #{added.Id}.");
}
static void ListExpenses(ExpenseStore store)
{
if (store.All.Count == 0)
{
Console.WriteLine("No expenses yet.");
return;
}
Console.WriteLine($"{"Id",3} {"Date",-10} {"Category",-12} {"Amount",10} Description");
foreach (Expense e in store.All.OrderBy(e => e.Date))
{
Console.WriteLine($"{e.Id,3} {e.Date:yyyy-MM-dd} {e.Category,-12} {e.Amount,10:N2} {e.Description}");
}
Console.WriteLine($"Total: {store.All.Sum(e => e.Amount):N2}");
}
static void ShowTotals(ExpenseStore store)
{
if (store.All.Count == 0)
{
Console.WriteLine("No expenses yet.");
return;
}
decimal grand = store.All.Sum(e => e.Amount);
var groups = store.All
.GroupBy(e => e.Category, StringComparer.OrdinalIgnoreCase)
.Select(g => new { Category = g.Key, Total = g.Sum(e => e.Amount), Count = g.Count() })
.OrderByDescending(x => x.Total);
foreach (var g in groups)
{
decimal percent = g.Total / grand * 100;
Console.WriteLine($"{g.Category,-12} {g.Total,10:N2} {percent,5:F1}% ({g.Count} items)");
}
}
static void DeleteExpense(ExpenseStore store)
{
ListExpenses(store);
if (store.All.Count == 0) return;
Console.Write("Id to delete: ");
if (int.TryParse(Console.ReadLine(), out int id) && store.Remove(id))
{
Console.WriteLine("Deleted.");
}
else
{
Console.WriteLine("No expense with that id.");
}
}
static string ReadText(string prompt)
{
while (true)
{
Console.Write(prompt);
string text = (Console.ReadLine() ?? "").Trim();
if (text.Length > 0) return text;
Console.WriteLine("This cannot be empty.");
}
}
static decimal ReadAmount(string prompt)
{
while (true)
{
Console.Write(prompt);
if (decimal.TryParse(Console.ReadLine(), out decimal amount) && amount > 0)
{
return amount;
}
Console.WriteLine("Enter a positive number, for example 450.75.");
}
}
static DateOnly ReadDate(string prompt)
{
while (true)
{
Console.Write(prompt);
string text = (Console.ReadLine() ?? "").Trim();
if (text.Length == 0) return DateOnly.FromDateTime(DateTime.Today);
if (DateOnly.TryParse(text, out DateOnly date)) return date;
Console.WriteLine("Use the format yyyy-mm-dd, for example 2026-03-15.");
}
}
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