Lesson 6 / 26

Classes and Records

Model data with classes and immutable records, and compare them correctly.

Class or record?

A class compares by reference by default. A record compares by value and gives you with copies and a readable ToString(). Use records for plain data such as API request and response shapes.

A record in action

Two records with equal values are equal. with makes a changed copy and leaves the original untouched.

public record Product(int Id, string Name, decimal Price);

var a = new Product(1, "Pen", 10m);
var b = new Product(1, "Pen", 10m);
Console.WriteLine(a == b);
var c = a with { Price = 12m };
Console.WriteLine(c);

Output:

True
Product { Id = 1, Name = Pen, Price = 12 }

Cheque vs address

Comparing classes by reference is like asking whether two people live at the same address. Comparing records by value is like asking whether two cheques show the same amount and payee.

Quick check: Which keyword makes a modified copy of a record?

  • copy
  • with
  • clone
  • new
Answer

with — `with { ... }` creates a new record with the listed properties changed.