Records & Record Structs in C#
Create immutable data types with record classes and record structs (C# 10+) — with expressions, deconstruction, inheritance, and value equality.
Introduction to Records
1. What is a Record?
A record is an immutable reference type optimized for holding data.
Creating Records
1. Positional Record Syntax
Declare properties in parentheses — the compiler generates everything.
2. Nominal Record Syntax
Declare records with explicit property bodies — more control.
3. Record with Validation
Add a compact constructor to validate data at construction time.
4. Mutable Records
Records are immutable by default, but you can make individual properties mutable by using `{ get; set; }` instead of `{ get; init; }`. The record still provides value equality and `ToString()` — just without the immutability guarantee.
Value Equality
1. Records Use Value Equality
Unlike classes, records with the same data are `==` equal.
with Expressions
1. Non-Destructive Mutation with with
`record with { Prop = newValue }` returns a new record with only that property changed.
Deconstruction
1. Deconstructing a Record
Positional records auto-generate `Deconstruct()` — unpack with tuple syntax.
Record Inheritance
1. Extending a Record
Records support inheritance — a derived record adds more properties.
record struct (C# 10+)
1. record struct vs record class
`record struct` lives on the stack — ideal for small, short-lived data.
Records vs Classes vs Structs
1. When to Use Each
Records, classes, and structs each suit different scenarios.