Records
Learn C# record types — a concise way to model immutable data with built-in value equality.
What is a Record?
Introduced in C# 9, a `record` is a reference type designed for modeling immutable data concisely — it automatically generates a constructor, properties, and value-based equality.
record Person(string Name, int Age);
var person = new Person("Diya", 28);Console.WriteLine(person); // ToString() is auto-generated tooConsole.WriteLine(person.Name);Click Run to see what this code prints.
Value Equality
Unlike a regular class (which compares by reference), two records with identical property values are considered equal.
var p1 = new Person("Diya", 28);var p2 = new Person("Diya", 28);
Console.WriteLine(p1 == p2); // True — value equality!The with Expression
`with` creates a new record based on an existing one, copying every property except the ones you override — ideal for immutable data.
var updated = person with { Age = 29 };Console.WriteLine(updated);Console.WriteLine(person); // original is unchangedClick Run to see what this code prints.
Records vs Classes
record
- Value equality by default
- Concise, auto-generated ToString()
- Ideal for DTOs and immutable data
class
- Reference equality by default
- Full control over behavior
- Ideal for entities with identity and mutable state
FAQs
By default their properties are init-only (settable only at creation), but you can still declare a mutable record if you explicitly need one — immutability is the convention, not a hard rule.
Summary
- Records are a concise way to model immutable data.
- They compare by value, not reference, by default.
- `with` creates a modified copy without mutating the original.