Records, structs and value equality
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
Two kinds of types
Every type in .NET is either a reference type or a value type. A class is a reference type. A variable holds a pointer to an object on the heap. Copying the variable copies the pointer, so two variables can see the same object. A struct is a value type. The data lives directly in the variable, and copying it copies all the data.
This difference decides how equality works, how much memory you allocate, and how bugs appear. When I review code, mistakes here are some of the most common I see.
Records: classes for data
A lot of classes exist only to carry data: an order line, a request, a result. You write the properties, then a constructor, then an Equals method, then GetHashCode, then ToString. A record gives you all of that in one line. The compiler writes the members.
var a = new Money(100m, "PKR");
var b = new Money(100m, "PKR");
Console.WriteLine(a == b); // True: compares values
Console.WriteLine(ReferenceEquals(a, b)); // False: two objects
Console.WriteLine(a); // Money { Amount = 100, Currency = PKR }
// Non-destructive mutation with 'with'
var discounted = a with { Amount = 80m };
Console.WriteLine($"{a.Amount} -> {discounted.Amount}");
// Positional deconstruction
var (amount, currency) = a;
Console.WriteLine($"{amount} {currency}");
// A record struct is a value type with the same features
var p1 = new Point(3, 4);
var p2 = p1 with { Y = 10 };
Console.WriteLine($"{p1} {p2} distance {p1.DistanceFromOrigin():F2}");
// A mutable struct trap
var counter = new Counter();
Counter copy = counter;
copy.Increment();
Console.WriteLine($"{counter.Value} vs {copy.Value}"); // 0 vs 1
// A class-based record with extra members and validation
var person = new Person("Sara", 31) { Email = "sara@example.com" };
Console.WriteLine(person);
record Money(decimal Amount, string Currency);
readonly record struct Point(double X, double Y)
{
public double DistanceFromOrigin() => Math.Sqrt(X * X + Y * Y);
}
struct Counter
{
public int Value;
public void Increment() => Value++;
}
record Person(string Name, int Age)
{
public string? Email { get; init; }
}
Walking through it
record Money(decimal Amount, string Currency); creates a class with two init-only properties, a constructor, and value-based equality. That is why a == b is true even though they are different objects. With an ordinary class, == compares references and the answer would be false. The generated ToString prints the property values, which makes logging and debugging much easier.
The with expression copies a record and changes the properties you name. The original is untouched. This supports a style where objects never change after creation. Immutable data is safer to share between threads and easier to reason about. I use records for DTOs, messages, configuration values and anything that represents a fact rather than a thing with a life cycle.
The Point type is a readonly record struct. It has the same equality and with behaviour, but it is a value type. Marking it readonly tells the compiler no member changes it. That allows optimisations and prevents the trap shown next.
The Counter example shows the classic mutable struct bug. Counter copy = counter; copies the whole struct. Calling Increment on the copy leaves the original at zero. If this surprises you, it will surprise your teammates as well. That is why the guidance is simple: make structs immutable.
Choosing between them
| Use | When |
|---|---|
class | An object with identity and behaviour that changes over time |
record | Immutable data compared by its values, mostly reference semantics |
readonly record struct | Small value-like data, such as a point or an amount, where you want to avoid heap allocation |
struct | Rare. Small, immutable, and created in huge numbers |
Microsoft's guidance is to consider a struct only for small types, roughly 16 bytes or less, that are immutable and short-lived. Larger structs cost more to copy than a reference would.
Equality in records
Record equality compares every property. If a property is a list, it compares the list reference, not the items. Two records holding different list objects with the same content are not equal. This surprises people. When a record must contain a collection and you need value comparison, you have to write your own Equals or compare the items separately.
Common mistakes
- Using a record for an entity that has identity, such as a database row with an id that changes state. Two rows with the same data are still different rows.
- Writing mutable structs. Copies change, originals do not, and nobody understands why.
- Assuming a record's list property is compared by content.
- Boxing. Putting a struct into an
objector an interface variable allocates on the heap, which removes the benefit.
Try it yourself
- Write a record
Address(string Street, string City). Create two equal addresses and a third that differs only in the city usingwith. - Make a
readonly record struct Temperature(double Celsius)with a calculatedFahrenheitproperty. - Add a
List<string>property to a record, create two equal-looking records, and check what==says. Explain it.
var a = new Money(100m, "PKR");
var b = new Money(100m, "PKR");
Console.WriteLine(a == b); // True: compares values
Console.WriteLine(ReferenceEquals(a, b)); // False: two objects
Console.WriteLine(a); // Money { Amount = 100, Currency = PKR }
// Non-destructive mutation with 'with'
var discounted = a with { Amount = 80m };
Console.WriteLine($"{a.Amount} -> {discounted.Amount}");
// Positional deconstruction
var (amount, currency) = a;
Console.WriteLine($"{amount} {currency}");
// A record struct is a value type with the same features
var p1 = new Point(3, 4);
var p2 = p1 with { Y = 10 };
Console.WriteLine($"{p1} {p2} distance {p1.DistanceFromOrigin():F2}");
// A mutable struct trap
var counter = new Counter();
Counter copy = counter;
copy.Increment();
Console.WriteLine($"{counter.Value} vs {copy.Value}"); // 0 vs 1
// A class-based record with extra members and validation
var person = new Person("Sara", 31) { Email = "sara@example.com" };
Console.WriteLine(person);
record Money(decimal Amount, string Currency);
readonly record struct Point(double X, double Y)
{
public double DistanceFromOrigin() => Math.Sqrt(X * X + Y * Y);
}
struct Counter
{
public int Value;
public void Increment() => Value++;
}
record Person(string Name, int Age)
{
public string? Email { get; init; }
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account