Records

A positional record

A record is a class with the parts a data type needs written for it: a constructor, a property per parameter, value equality, a readable ToString, a with copy and deconstruction. One line declares all of that:

var first = new Person("Anna", "Kyiv"); var second = new Person("Anna", "Kyiv"); var third = first with { City = "Lima" }; Console.WriteLine(first); Console.WriteLine($"equal {first == second}"); Console.WriteLine($"copy {third}"); Console.WriteLine($"still equal {third == first}"); record Person(string Name, string City);

dotnet run

Person { Name = Anna, City = Kyiv }
equal True
copy Person { Name = Anna, City = Lima }
still equal False

The two people are different objects and still compare equal, which is the difference from a class: a record compares its values, a class compares its references unless it overrides Equals. The ToString line is generated too, with the type name and every property in the order they were declared.

Value equality

The with expression of the first program is the other half of the value story:

Two records are equal when they are of the same type and every property is equal, and equal records have equal hash codes, which is what makes a record usable as a dictionary key:

var person = new Person("Anna", "Kyiv"); var (name, city) = person; Console.WriteLine($"{name} lives in {city}"); Console.WriteLine($"hash equal {person.GetHashCode() == new Person("Anna", "Kyiv").GetHashCode()}"); record Person(string Name, string City);

dotnet run

Anna lives in Kyiv
hash equal True

The deconstruction var (name, city) = person is the generated Deconstruct method in action. A record overrides Equals and GetHashCode together, which is why two equal records also have equal hash codes: a type that overrides only one of them breaks every dictionary that holds it.

A record with a body

A record may carry members of its own: a computed property, a method, an override of ToString that reads better than the generated one. The positional parameters are in scope in the body, as with a primary constructor.

var order = new Order("A-1", 3, 2.50m); Console.WriteLine(order); Console.WriteLine($"total {order.Total:F2}"); record Order(string Id, int Quantity, decimal Price) { public decimal Total => Quantity * Price; public override string ToString() => $"{Id}: {Quantity} x {Price:F2} = {Total:F2}"; }

dotnet run

A-1: 3 x 2.50 = 7.50
total 7.50

The override replaced the generated text, and Total is not part of equality: only the positional properties are compared. That is the rule to remember when a record grows a computed member: two orders with the same id, quantity and price are equal even if one of them was built by a different code path.

A field that breaks equality

The generated equality compares each property with EqualityComparer<T>.Default. For an array that comparer is reference equality, so two records with identical contents are not equal:

var first = new Bag(new[] { 1, 2 }); var second = new Bag(new[] { 1, 2 }); Console.WriteLine($"equal {first == second}"); Console.WriteLine($"same array {ReferenceEquals(first.Items, second.Items)}"); record Bag(int[] Items);

dotnet run

equal False
same array False

The two arrays hold the same numbers and are still different arrays, so the records differ. A record that holds a collection and must compare by content either replaces the generated equality, the strongly typed Equals and GetHashCode, with a sequence comparison, or keeps the collection out of the record and compares it where it is used. The lesson on operators and IEquatable comes back to the override.

Exercises

  1. Add a third property to Person and watch what the generated ToString prints.
  2. Put two equal people in a HashSet and count the items.
  3. Copy an order with with { Quantity = 10 } and print both totals.
  4. Override Equals on Bag so that two bags with the same numbers are equal. Read the warning about GetHashCode first.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a positional record generate?

    Answer

    Properties, a constructor, value equality, ToString, with and Deconstruct

    The record syntax asks the compiler for the whole set a data type needs.

  2. How do two records of the same type with equal properties compare with ==?

    Answer

    Equal, by value

    A record overrides the equality operators to compare the values.

  3. What does this program print? var a = new P("x"); var b = a with { N = 2 }; Console.WriteLine(a.N + b.N); record P(string Name) { public int N { get; init; } = 1; }

    Answer

    3

    The copy sets N to 2, the original keeps 1, and the sum is 3.

  4. What is shallow about a record copy made with with?

    Answer

    A reference property is copied as the same reference

    with copies the fields, and a field of a reference type is a reference.

  5. Why are two records holding equal arrays not equal?

    Answer

    The array property compares by reference

    The default comparer for an array is reference equality, so the contents do not matter.

  6. What does this program print? var p = new P("a", "b"); var (x, y) = p; Console.WriteLine($"{y}-{x}"); record P(string First, string Second);

    Answer

    b-a

    Deconstruction follows the parameter order, so x is First and y is Second.

  7. Which member is not part of a record equality check?

    Answer

    A computed property declared in the body

    Only the positional properties and the fields of the record take part in the generated equality.

  8. What is a record best used for?

    Answer

    Data that is compared and copied by value

    Value equality and with make a record a good fit for messages, rows and other data values.

  9. Can a record inherit from another record?

    Answer

    Yes, a record may derive from a record

    Record inheritance is supported and the generated equality accounts for the runtime type.

  10. What does record Person(string Name, string City); declare for Name?

    Answer

    An init-only property with a getter

    Positional parameters become init-only properties, so the record stays immutable after building.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image