Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 182 ยท Classes and Objects

Records

Learn C# records - positional records, value equality, with-expressions, deconstruction, init-only properties, inheritance, record struct and readonly record struct, with runnable examples.

A great many classes exist only to carry data: a point with X and Y, a money amount with a currency, one row from a file. Writing such a class by hand means properties, a constructor, Equals, GetHashCode and ToString, around forty lines in which a small slip creates bugs that are hard to see (see The object Class). A record (C# 9) declares the same thing in one line:

C#
public record Point(int X, int Y);

The compiler writes the rest. More importantly, a record makes a promise to the reader: this type is its data. Two records with equal data are equal, copying one with a few changes is a single expression, and it is natural to make them immutable. This lesson covers positional records, what the compiler generates, with expressions, deconstruction, inheritance, record struct and readonly record struct, and when records are, and are not, the right choice.

A first record

C# Everything a one-line record gives you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

a and b are two different objects (ReferenceEquals is false) but they hold the same data, so == and Equals say they are equal and they have the same hash code. That makes records excellent dictionary keys and set elements. The generated ToString prints the name and the properties in braces, which is useful in logs and tests.

The parenthesized list is the primary constructor, and a record with it is called a positional record. For each parameter the compiler creates a public property named after it (by convention PascalCase, as here) with an init accessor, meaning it can be set during construction or in an object initializer, and never afterwards.

What the compiler generates

For record Point(int X, int Y) you get:

  • a class Point (a reference type) with the properties X and Y, set through init;
  • a constructor taking X and Y;
  • Equals(Point?), Equals(object?), GetHashCode(), and the == and != operators, all comparing every field;
  • ToString() in the form Point { X = 3, Y = 4 };
  • a Deconstruct method (positional records only);
  • a hidden copy constructor and Clone-like method behind with expressions.

Because properties are init-only, a record is shallowly immutable by default: you cannot reassign X after creation. The word shallowly matters, and we return to it below.

C# Init-only properties reject later assignment (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler stops with error CS8852: Init-only property or indexer 'Point.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. To change a record you create a changed copy, which is what the next section is about.

with expressions: non-destructive mutation

Instead of modifying an object, make a copy with some properties changed:

C# Copying with with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

with copies every property from the source and then applies the changes in the braces. The source never changes, which is ideal for state that flows through a program (UI state, configuration, messages): you can keep the old value, compare it with the new one, and never worry that someone else mutated it behind your back.

Records versus classes you write by hand

You can also declare a record with ordinary property syntax. That is how you add validation, extra members or mutable properties:

C# A record with a body, validation and extra members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You can override ToString (as here) or the generated equality if you must. Note that with { Amount = ... } bypasses your constructor's validation because it uses the hidden copy constructor, then sets init properties; if validation matters for every property, put it in the init accessor (using the field keyword or a backing field) rather than only in the constructor.

For positional records, you can also add your own members and even replace a generated property with one of your own, as long as it has the same name and type:

C#
record Temperature(double Celsius)
{
    public double Fahrenheit => Celsius * 9 / 5 + 32;     // extra computed member
}

Deconstruction

Positional records get a Deconstruct method, so you can unpack them into variables, in a foreach, or in patterns:

C# Deconstructing and pattern matching a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Records and pattern matching are made for each other. Property patterns like { Distance: 0 } read the generated properties, and positional patterns use Deconstruct.

Shallow immutability: the catch

Init-only properties stop reassignment, but if a property holds a mutable object, you can still change that object. Two records with a shared list also share its changes:

C# Records are only shallowly immutable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The copy shares the same List, so adding to it changes the original too. And record equality compares the Members reference, not its contents, so one == two is false. When you need real immutability, use IReadOnlyList<T> with an immutable collection (Immutable Collections) or ImmutableArray<T>, and remember that those compare by reference as well.

Inheritance with records

A record class can inherit from another record (not from an ordinary class, and not the other way round). Equality takes the runtime type into account, so a Student is never equal to a Person even if the shared properties match:

C# Record inheritance and equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Records can implement interfaces, and you can mark a record sealed or abstract. The inheritance rules from Inheritance apply, so keep hierarchies small.

record struct and readonly record struct

Records come in two flavors. record (or record class) is a reference type. record struct (C# 10) is a value type with the same generated members. Choose it for small, short-lived values where allocation matters.

Declaration Kind Properties Typical use
record Point(int X, int Y) reference init (immutable) DTOs, messages, domain values
record struct Point(int X, int Y) value mutable get; set; small value you want to mutate
readonly record struct Point(int X, int Y) value init (immutable) small immutable values, keys

A detail that catches people: in a non-readonly record struct, the positional properties are mutable. Add readonly for immutability.

C# record struct versus readonly record struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choose between class and struct for the usual reasons (Structs): a record struct avoids a heap allocation and is copied on assignment, but copying a big struct is slower than passing a reference. As a rule, use a readonly record struct for tiny (up to about 16 bytes) immutable values, and a record class otherwise.

When to use records, and when not

Use a record when:

  • the type represents data and equality should be by value (coordinates, money, ids, events, API request and response bodies);
  • you want immutability and easy "copy with changes";
  • you want free ToString, equality, and deconstruction.

Use a class when:

  • identity matters more than data: an Account or Customer entity that changes over time and is the same customer even when its name changes (many ORMs also expect classes with settable properties);
  • the type is mostly behavior and carries little data;
  • you need a deep inheritance hierarchy or a base class that is not a record.

Records do not replace classes; they are classes (or structs) with a generated, data-focused shape. If you only want a constructor that captures parameters, without the equality and with, look at Primary Constructors on ordinary classes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two instances of record Point(int X, int Y) both hold (3, 4). What does == return?

    Records generate value-based equality and the == operator compares all members, so equal data gives true. ReferenceEquals would still be false.
  2. 2. What does var b = a with { X = 5 }; do?

    with makes a non-destructive copy and applies the listed changes to the copy.
  3. 3. In record struct Point(int X, int Y); (without readonly), are X and Y mutable?

    Plain record structs generate get/set properties. Add readonly (readonly record struct) to make them init-only.
  4. 4. Why can two records with equal List properties still compare as not equal?

    Record equality calls each member's Equals. A List<T> uses reference equality, so two separate lists with the same items are not equal.
  5. 5. Which situation fits a regular class better than a record?

    Entities are defined by identity, not by their current data, so value equality would be wrong. Records suit data-defined values.

Summary

  • record Point(int X, int Y); generates properties, constructor, value equality, ToString, with support and Deconstruct.
  • Positional record properties are init-only: change a record by copying it with with.
  • Records are only shallowly immutable and compare members with their own Equals; mutable collection properties break the picture.
  • A record can inherit from another record; equality includes the runtime type.
  • record struct is a mutable value type, readonly record struct an immutable one; use them for small values.
  • Choose records for data defined by its values, classes for entities defined by identity.

Next: Structs