Records
Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 6 of 20.
A record is a type made to hold data. One line declares it, with a constructor and a read-only property for each value:
public record Book(string Title, string Author, int Year);Records print their values and compare by value: two records with the same values are ==, while two class objects are equal only when they are the same object. The properties cannot be changed after creation; with makes a changed copy instead.
var dune = new Book("Dune", "Frank Herbert", 1965);
Console.WriteLine(dune);
Console.WriteLine(dune == new Book("Dune", "Frank Herbert", 1965));
var reprint = dune with { Year = 2005 };This prints Book { Title = Dune, Author = Frank Herbert, Year = 1965 } and True. A type can live in its own file, such as Book.cs, and every file of a project compiles together.
Challenge
EasyAn expense is a name, an amount and a category. Give it a record, and let add take a category.
- In
Expense.cs, declarepublic record Expense(string Name, decimal Amount, string Category); - In the
addcase ofProgram.cs, after the amount is parsed, setcategorytoargs[3]whenargs.Length > 3, and to"other"when there is no fourth word. - Create
var expense = new Expense(args[1], amount, category);and print theAddedline from its properties, with the category in parentheses at the end:Added Lunch: 12.50 (food)dotnet run -- add Bus 3printsAdded Bus: 3.00 (other). - Change the usage message to
Usage: add <name> <amount> [category]. The square brackets mark the category as optional.
Try it: the terminal beside the editor already reads dotnet run -- add Lunch 12.50 food, so press Run: Added Lunch: 12.50 (food). Change the arguments to add Bus 3 and Run again: Added Bus: 3.00 (other).
Try it yourself
using System.Globalization;
var count = 0;
var total = 0m;
if (args.Length == 0)
{
Console.WriteLine("Expense Tracker");
Console.WriteLine($"{count} expenses");
Console.WriteLine($"Total: {total:F2}");
}
else
{
switch (args[0])
{
case "add":
if (args.Length < 3)
{
Console.Error.WriteLine("Usage: add <name> <amount>");
return 1;
}
if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
{
Console.Error.WriteLine($"Invalid amount: {args[2]}");
return 1;
}
Console.WriteLine($"Added {args[1]}: {amount:F2}");
break;
default:
Console.Error.WriteLine($"Unknown command: {args[0]}");
return 1;
}
}
return 0;
This lesson includes a short quiz. Start the lesson to answer it and track your progress.