What are records in C#, and how do they differ from classes and structs?
Short answer
A record is a reference type purpose-built for representing immutable data, distinguished from an ordinary class by using value-based equality by default (two records with identical property values are considered equal, even as separate instances) rather than the reference-based…
Advertisement
AModel answer
A record is a reference type purpose-built for representing immutable data, distinguished from an ordinary class by using value-based equality by default (two records with identical property values are considered equal, even as separate instances) rather than the reference-based equality classes use -- records also support the 'with' expression for producing a modified copy without mutating the original. Structs, by contrast, are value types living on the stack, best suited to small, lightweight data that doesn't need inheritance; classes remain the right choice for mutable objects with real behavior.
public record Person(string Name, int Age);
var p1 = new Person("Alice", 30);
var p2 = new Person("Alice", 30);
Console.WriteLine(p1 == p2); // True -- value-based equality, unlike an equivalent class
var older = p1 with { Age = 31 }; // non-destructive copy
Console.WriteLine(p1.Age); // 30, unchanged
Console.WriteLine(older.Age); // 31Real-world example
An API returning immutable response DTOs models them as records, getting automatic, correct value-based equality (useful in unit tests comparing expected vs actual responses) and the 'with' expression for building slightly-modified test fixtures, without hand-writing Equals()/GetHashCode() overrides.
Likely follow-ups
- Why does a record's default equality behavior sometimes surprise developers used to classes?
- When would a struct actually outperform an equivalent record for the same small piece of data?
Related topics