Glossary / Records

Records

Records are C# class or struct types with compiler-generated data-oriented behavior, including value-based equality, a readable ToString, and nondestructive copying with with. The record modifier adds these features while the underlying record class or record struct still determines reference or value assignment semantics.

Record forms and equality

record Person(string Name) is shorthand for a record class with a positional property and constructor. record struct Point(int X, int Y) is a value type. Record classes compare by record equality over their components rather than identity; record structs also compare by values. Equality includes the declared data members and can be customized, so mutable members may make hash-based collection behavior unsafe if changed after insertion.

public record Person(string Name, string City);
var original = new Person("Ada", "London");
var updated = original with { City = "Budapest" };

A with expression creates a shallow copy: referenced nested objects remain shared. Positional records synthesize properties (init-only for record classes, with details differing by form); records can also declare non-positional members. Record inheritance is supported for record classes with equality contracts; record structs cannot inherit from other structs/classes.

Choosing records

Use records for data whose equality is based on its values and where nondestructive updates are useful. Use classes for identity-oriented entities and mutable lifecycle behavior. Use record structs for small copyable values. Records are not automatically deeply immutable: init limits assignment after initialization but referenced collections can still mutate.

Interview questions

  1. Does record always mean value type? No; plain record means record class; record struct is a value type.
  2. What does with do? Creates a shallow copy with selected members changed.
  3. Are records deeply immutable? No; referenced objects may remain mutable/shared.
  4. How does equality differ from a normal class? Record equality compares record data by value by default.
  5. When prefer a class? When object identity and lifecycle/state matter more than value equality.

References