C# 9 Records — Silent GC Pile-Up from 'with' Expressions
Each 'with' allocates a new record — 2.4k alloc/s at 300 ords/s caused 12s GC pauses.
20+ years shipping production .NET services in enterprise systems. Everything here is grounded in real deployments.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- Records are reference types with value equality and init-only properties, generated by the compiler.
- Use records for immutable data snapshots—DTOs, value objects, domain events.
- 'with' expressions create shallow copies; nested mutable objects are shared, not cloned.
- Equality checks include runtime type (EqualityContract) — derived records never equal base records.
- Performance trap: every 'with' allocates a new object — high-frequency use causes GC pressure.
- Biggest mistake: expecting deep immutability when a property holds List
or other mutable classes.
Imagine you're filling out a form at the doctor's office. Once it's stamped and filed, nobody is allowed to scribble over your name or date of birth — the record is sealed. If they need to update something, they make a fresh copy of the form with just that one field changed. That's exactly what a C# Record is: a sealed snapshot of data. Two forms with identical information are considered the same record, even if they're physically two different pieces of paper — unlike a regular class object, which is only 'equal' if it's literally the same piece of paper.
Every non-trivial C# application is filled with objects whose only job is to carry data — API responses, domain events, configuration snapshots, query results. For years, developers wrote class after class, manually implementing Equals, GetHashCode, and ToString just to get predictable, safe data containers. That's hours of ceremony for something that should be a one-liner. C# 9, released with .NET 5 in November 2020, introduced Records to solve exactly this problem.
The core pain records fix is the gap between how we think about data objects and how classes actually behave. When you compare two class instances, C# asks 'are these the same object in memory?' — reference equality. But when you compare two shipping addresses or two money amounts, you want to ask 'do they contain the same values?' — value equality. Before records, achieving this required implementing four or five methods by hand every single time, and one typo in GetHashCode could cause subtle, hard-to-find bugs in collections.
By the end of this article you'll understand exactly what records are, how positional syntax and 'with' expressions work, when to reach for a record instead of a class or struct, and the three mistakes that trip up developers who are new to them. You'll also walk away knowing how to confidently answer the record questions that show up in C# interviews.
What a Record Actually Is (and What It Generates for You)
A record in C# 9 is a reference type — built on a class under the hood — but with a radically different set of defaults baked in by the compiler. When you declare a record, the compiler generates: structural equality (Equals and GetHashCode based on property values), a human-readable ToString, a protected copy constructor, and support for deconstruction. You get all of that for free.
The simplest record uses positional syntax: a single line where you list your properties inside parentheses. The compiler turns those into public init-only properties — meaning they can be set during object initialisation but never mutated afterwards. This immutability-by-default is the point. Records are designed to represent data that doesn't change after it's created.
Think of records as the right tool when your object IS its data. A Money value, an OrderId, a GPS coordinate, a User from an API response — these are records. A ShoppingCart that accumulates items, a DatabaseConnection that opens and closes — those are classes. The distinction is behavioural: records have data and identity through their values; classes have data plus mutable state and behaviour.
GetHashCode(), ToString(), and a protected copy constructor called 'Clone'. Understanding this makes records far less magical and helps you debug edge cases.'with' Expressions: Updating Immutable Records Without the Pain
Immutability sounds great until you need to change one field. With a regular immutable class you'd have to call the constructor again and manually pass every single property — even the ones you're not changing. For a record with eight properties, that's eight arguments just to update one value. Nightmare.
C# 9 introduces the 'with' expression to solve this. It creates a new record instance that is a copy of the original, with only the properties you specify changed. The original is untouched. Under the hood, 'with' calls the compiler-generated protected copy constructor (sometimes called the clone constructor), then applies a set of property initialisers.
This pattern is everywhere in functional programming and is the backbone of state management systems like Redux. In C# it lets you model things like 'apply a discount to this price' or 'mark this order as shipped' without mutating the original object — making your code far easier to reason about, test, and debug. If a bug is reported with a specific order state, you can reproduce it exactly because that state never changed after it was created.
Records vs Classes vs Structs: Choosing the Right Tool
The question developers ask most often is 'when do I use a record instead of a class?' The honest answer comes down to three things: immutability, equality semantics, and size.
Use a record when your type IS its data — an immutable snapshot where two instances with identical values should be considered the same thing. API DTOs, domain value objects (Money, EmailAddress, DateRange), event sourcing events, command objects, and configuration snapshots are all textbook records.
Use a class when your type has mutable state, behaviour-heavy logic, or identity that's separate from its data. A UserSession, a DatabaseConnection, or a ShoppingCart accumulates state over time — the 'same' cart from a minute ago is still the same cart even if the items changed. That's a class.
Use a struct when you need stack allocation for small, frequently-created value types — think Vector2, RGBA colour, or a cache key. C# 10 introduced record structs if you want value semantics plus records' equality machinery, but for C# 9 the sweet spot is: structs for tiny, perf-critical value types; records for immutable data objects; classes for everything that has mutable state and behaviour.
Inheritance and Record Hierarchies: Powerful but with Limits
Records support single-level inheritance, and this is where they really shine for modelling domain events or discriminated-union-style hierarchies. A base record can hold shared properties, and derived records add specifics. The 'with' expression and equality both respect the actual runtime type — a crucial detail that catches people out.
Records cannot inherit from classes (other than object), and classes cannot inherit from records. The inheritance chain must be all records. This keeps the equality contract consistent — you'd get bizarre results if a record's Equals method had to compare itself against an arbitrary class hierarchy.
When you compare two records for equality, the runtime type must match. A base record instance is NOT equal to a derived record instance, even if all the base properties are identical. This is the correct behaviour — they represent different concepts — but it surprises developers who are coming from manually written Equals implementations that check only specific properties.
Performance Considerations and When to Use Mutable Fallbacks
Records are not free. Every 'with' expression allocates a new object on the heap. The compiler-generated Equals and GetHashCode use reflection-like mechanisms (EqualityComparer
Consider the scenario: a real-time telemetry system processing 10,000 sensor readings per second. Each reading is a record with 12 fields. Every update to a reading uses 'with' to change a single field (e.g., temperature). That's 10,000 record allocations per second just for updates — plus the original records. In less than a minute, you've generated over a million short-lived objects. The Gen0 GC will fire frequently, causing micro-stalls.
The fix is straightforward: use a mutable class for the hot processing loop, then convert to a record at the boundary when you need to persist or send the data. Or use pooled record instances with a reset pattern. Another option: use a record struct (C# 10) which lives on the stack and avoids heap allocation entirely, though you lose inheritance and reference semantics.
Another hidden cost: records with many properties generate large Equals implementations. If you frequently compare records with 20+ fields, the per-comparison cost adds up. Consider using a simplified equality if you only need a subset of fields to match.
- Record 'with' expression always creates a new object on the heap.
- The copy constructor copies all fields, even if only one changes.
- High-frequency use (thousands/sec) can overwhelm the GC.
- Mutable classes reuse the same memory — no allocation for new state.
- Strategy: use mutable types in hot paths, convert to records at boundaries.
Why Records Break Your Serialization Contracts (And How to Fix It)
Records generate compiler-synthesized properties with init setters. That sounds great for immutability until your JSON deserializer tries to hydrate an object and fails because Newtonsoft.Json doesn't respect init out of the box. The same goes for Dapper, Entity Framework, or any tool that calls public setters. Production logs fill with 'Property setter not found' exceptions. The fix: use System.Text.Json (settings.JsonSerializerOptions.IncludeFields = true) or stick to positional records where the compiler generates a Deconstruct method that plays nicely with deserializers. If you need legacy serializer support, don't use init without checking the serializer's compatibility matrix first. The reason this matters: silent data loss from half-initialized objects is far worse than a compile error.
init accessors work with third-party serializers. Always write a unit test that round-trips a record through your pipeline before code review.The Hidden Cost of 'record' on Hot Paths: Stack Allocations or Heap Pressure?
Developers pick records thinking they get class-like semantics with less boilerplate. But record class is a reference type — each allocation goes on the heap. In tight loops (game loops, high-frequency trading, or real-time processing), every new on a record creates GC pressure. record struct fixes this: stack allocation, no GC overhead, but you lose inheritance. The decision matrix is straightforward: if your record lives longer than a single method call, use record class. If it's ephemeral — immediate computation then discard — use record struct. The readonly record struct modifier eliminates defensive copies in method parameters. Measure allocation with BenchmarkDotNet before optimizing. Do not guess. The reason: a 5% GC pause in a trading system costs real money; a 5% GC pause in an admin panel is invisible.
record struct is your friend for DTOs in hot paths, but never use it with inheritance hierarchies. It's a trade-off, not a free lunch.record struct = stack, record class = heap. Choose based on object lifespan, not dogma.Record Structs in C# 10+
C# 10 introduced record structs, combining value-type semantics with the immutability and syntactic convenience of records. Unlike record classes (reference types), record structs are value types, meaning they are copied on assignment and stored on the stack (or inline in other objects). This eliminates heap allocation and reduces GC pressure, making them ideal for high-performance scenarios where immutability is desired but heap overhead is unacceptable.
To declare a record struct, use readonly record struct for full immutability or record struct for mutable fields (though the latter is rarely used). For example:
``csharp public readonly record struct Point(double X, double Y); ``
This generates a value type with positional construction, ToString(), Equals(), GetHashCode(), Deconstruct, and ==/!= operators. The readonly modifier ensures all fields are readonly, enforcing immutability.
Record structs support with expressions, but unlike class records, they do not generate a copy constructor; instead, the compiler creates a new instance by copying and modifying fields. This is efficient because value types are small and stack-allocated.
However, record structs have limitations: they cannot inherit from other record structs (structs cannot inherit), and they should be kept small (typically under 16-24 bytes) to avoid excessive copying. For larger immutable data, record classes remain the better choice.
Performance-wise, record structs eliminate heap allocations entirely. In tight loops, using a record struct instead of a record class can reduce GC collections by orders of magnitude. For example, processing 1 million points as record structs avoids 1 million heap allocations, whereas record classes would trigger frequent GC pauses.
With Expressions for Non-Destructive Mutation
with expressions are a hallmark of records, enabling non-destructive mutation: creating a new instance with modified properties while leaving the original unchanged. This is syntactic sugar over the compiler-generated copy constructor (for class records) or field-wise copy (for struct records).
Under the hood, with expressions call a protected copy constructor that performs a shallow copy of the record's backing fields, then applies the specified property changes. For example:
``csharp var original = new Person("Alice", 30); var updated = original with { Age = 31 }; ``
This creates a new Person instance with Name copied from original and Age set to 31. The original remains unchanged.
For record structs, with expressions do not use a copy constructor; instead, the compiler generates code that copies the struct and modifies the specified fields. This is more efficient for value types.
Performance considerations: Each with expression on a record class allocates a new object on the heap, increasing GC pressure. In hot paths, this can cause significant overhead. For example, updating a single field in a loop of 1 million iterations creates 1 million heap allocations. Mitigation strategies include: - Using mutable fallbacks (e.g., regular classes) for high-frequency updates. - Using record structs to avoid heap allocation entirely. - Batching updates to reduce the number of with calls.
with expressions also work with anonymous types and can be chained, but each chain step creates an intermediate allocation. For complex updates, consider using a builder pattern or mutable DTOs.
Finally, with expressions respect inheritance: they preserve the runtime type of the record, so if you have a derived record, the new instance will be of the derived type.
with expressions in loops. Instead, use mutable builders or record structs. For example, in a game engine updating entity positions, use readonly record struct to avoid allocations entirely.with expressions provide a clean, immutable update pattern but come with allocation costs for class records; use record structs or mutable alternatives in hot paths.Records vs Classes vs Structs: Decision Guide
Choosing between records, classes, and structs depends on your data's size, mutability needs, and performance requirements. Below is a decision guide with performance data.
Records (class): Reference type, immutable by default, value equality. Best for DTOs, domain events, and data that benefits from structural equality. Heap-allocated; each with expression creates a new object. Allocation overhead: ~32 bytes + fields.
Classes: Reference type, mutable by default, reference equality. Best for long-lived objects, services, and entities with identity. Heap-allocated; mutations do not allocate new objects. Allocation overhead: ~24 bytes + fields.
Structs: Value type, mutable or immutable, value equality. Best for small, frequently created data (e.g., coordinates, colors). Stack-allocated (or inline); no heap allocation. Copy overhead on assignment. Limit size to <16-24 bytes to avoid performance degradation.
Record Structs: Value type, immutable (if readonly), value equality. Combines struct performance with record syntax. Ideal for small immutable data in hot paths.
Performance Data (approximate, per 1 million operations): - Class allocation: 1 million objects, ~24 MB heap, GC gen0 collections ~10-20. - Record class with: 1 million objects, ~32 MB heap, GC gen0 collections ~15-25. - Struct copy: 1 million copies, 0 heap, 0 GC. - Record struct with: 1 million copies, 0 heap, 0 GC (if small).
Decision Matrix: | Scenario | Recommendation | |----------|----------------| | Immutable, value equality, heap OK | Record class | | Mutable, reference equality | Class | | Small, frequent creation, immutable | Record struct | | Small, frequent creation, mutable | Mutable struct (careful) | | Large data (>24 bytes) | Class or record class | | Hot path, no allocations allowed | Record struct or mutable struct |
In practice, profile your application. For most business applications, records are fine. For high-performance computing, favor structs.
readonly record struct for telemetry data points processed millions of times per second.The Silent GC Pile-Up: 300 Orders Created per Second
- Every 'with' expression allocates a new object — do not use records in tight, high-frequency loops.
- Instrument allocation rates with dotnet-counters before assuming record overhead is negligible.
- Reserve records for boundary snapshots (API responses, events) — never for intermediate state in a hot path.
dotnet-counters monitor --process-id <pid> --counters System.Runtimedotnet-dump collect --process-id <pid>| File | Command / Code | Purpose |
|---|---|---|
| BasicRecordDemo.cs | using System; | What a Record Actually Is (and What It Generates for You) |
| WithExpressionDemo.cs | using System; | 'with' Expressions |
| RecordVsClassComparison.cs | using System; | Records vs Classes vs Structs |
| RecordInheritanceDemo.cs | using System; | Inheritance and Record Hierarchies |
| PerformanceComparison.cs | using System; | Performance Considerations and When to Use Mutable Fallbacks |
| RecordSerializer.cs | using System.Text.Json; | Why Records Break Your Serialization Contracts (And How to F |
| RecordPerformance.cs | using BenchmarkDotNet.Attributes; | The Hidden Cost of 'record' on Hot Paths |
| RecordStructExample.cs | public readonly record struct Point(double X, double Y); | Record Structs in C# 10+ |
| WithExpressionExample.cs | public record Person(string Name, int Age); | With Expressions for Non-Destructive Mutation |
| DecisionGuideExample.cs | public record ProductDto(int Id, string Name, decimal Price); | Records vs Classes vs Structs |
Key takeaways
Interview Questions on This Topic
What is the difference between a record and a class in C# 9, and can you give a concrete example of when you'd choose each one?
Frequently Asked Questions
20+ years shipping production .NET services in enterprise systems. Everything here is grounded in real deployments.
That's C# Basics. Mark it forged?
8 min read · try the examples if you haven't