Lesson 22 of 34 · Classes & Objects
C# Records: Immutable Data with Value Equality
Many objects in a program are just data: a coordinate, a price tag, a log entry, an item in a shop. For these, C# has records — a compact way to declare types that hold values, are immutable by default and compare by their contents instead of by reference.
A record in one line
public record Point(int X, int Y);
This single line declares a type with a constructor, two init-only properties X and Y, and a lot of useful behaviour generated by the compiler:
var a = new Point(3, 4);
Console.WriteLine(a.X); // 3
Console.WriteLine(a); // Point { X = 3, Y = 4 }
// a.X = 10; // compile error: records are immutable
Value equality
Two class objects are equal only when they are the same object. Two records are equal when all their values are equal:
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
Console.WriteLine(p1 == p2); // True (record: same values)
Console.WriteLine(ReferenceEquals(p1, p2)); // False (still two objects)
That makes records perfect for things you compare, use as dictionary keys or put in sets.
Non-destructive changes with with
You cannot change a record, but you can create a modified copy with a with expression:
public record Hero(string Name, int Level, string Weapon);
var aria = new Hero("Aria", 7, "Bow");
var promoted = aria with { Level = 8 };
Console.WriteLine(aria.Level); // 7 — the original is untouched
Console.WriteLine(promoted.Level); // 8
Deconstruction
Positional records can be taken apart into variables:
var (name, level, weapon) = aria;
Console.WriteLine($"{name} uses a {weapon}");
Adding members
A record can have a body with extra properties and methods, just like a class:
public record Order(string Item, int Quantity, decimal UnitPrice)
{
public decimal Total => Quantity * UnitPrice;
public bool IsBulk => Quantity >= 10;
}
You can also write records with normal property syntax (public record Settings { public int Volume { get; init; } }), and record struct creates a small value-type record.
Record or class?
Use a record for data whose identity is its values: money amounts, coordinates, messages, results. Use a class for things with an identity and changing state, like a bank account or a game character — two accounts with the same balance are still different accounts.
Common mistakes
- Trying to modify a property: use
withto make a changed copy. - Ignoring the result of
with:item with { Price = 5 };on its own creates a copy and throws it away. - Records with mutable collections: a
List<T>inside a record can still be changed, and equality compares the list reference, not its items.
Assignment
- The positional record
Item(string Name, int Weight, decimal Price)is declared for you — read it and notice how little code it takes. - The record
Coordinate(int X, int Y)needs a working computed propertyDistance— the "taxicab" distance from the origin,|X| + |Y|. - In
Shop:Discount(item, percent)returns a copy of the item with the price lowered bypercentpercent and rounded to 2 decimals: 20% off12.50is10.00. The original must not change.SameItem(a, b)returnstruewhen two items have equal values.Heaviest(items)returns the heaviest item of a non-empty list (the first one if several tie).
Premium lesson
Unlock the full Learn C# course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Value objects and equality in other languages
- Python Dataclasses · Python
- Java toString(), equals() and hashCode() · Java
Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.
Lesson last updated on .