Tutorials / Advanced C# and .NET / Records, structs and value equality

Records, structs and value equality

14 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. 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

UseWhen
classAn object with identity and behaviour that changes over time
recordImmutable data compared by its values, mostly reference semantics
readonly record structSmall value-like data, such as a point or an amount, where you want to avoid heap allocation
structRare. 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 object or an interface variable allocates on the heap, which removes the benefit.

Try it yourself

  1. Write a record Address(string Street, string City). Create two equal addresses and a third that differs only in the city using with.
  2. Make a readonly record struct Temperature(double Celsius) with a calculated Fahrenheit property.
  3. Add a List<string> property to a record, create two equal-looking records, and check what == says. Explain it.
csharp
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