skip to content

In C#, what does the compiler generate when you declare a positional record such as record Money(decimal Amount, string Currency)?

level: juniorimportance: must knowfreq 75%

answer

  1. one line, many members
  2. init-only, not read-write
  3. primary constructor plus Deconstruct
  4. Equals, GetHashCode, == and ToString

basics

~20 s

A positional record gets a public init-only property per parameter, a primary constructor, a Deconstruct method, value-based Equals, GetHashCode, == and !=, a ToString listing its public members, and the copy members that with uses.

solid answer

~40 s

`record Money(decimal Amount, string Currency)` declares a reference type. For each positional parameter the compiler writes a public `get; init;` auto-property, plus a public primary constructor that sets them and `Deconstruct(out decimal Amount, out string Currency)`. Every record class, positional or not, also gets value equality: an `Equals(object?)` override, `Equals(Money?)` implementing `IEquatable<Money>`, `GetHashCode`, `==` and `!=`, and an `EqualityContract` property returning `typeof(Money)`. It gets a `ToString` that prints `Money { Amount = 12.50, Currency = EUR }` through a `PrintMembers` helper, and a hidden clone method with a copy constructor for `with`. A nominal record, which declares its properties in the body, gets the same equality, printing and copy members but no primary constructor and no `Deconstruct`.

code

csharp · 20 lines
csharp
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // fixed decimal separator

var a = new Money(12.50m, "EUR");
var b = new Money(12.50m, "EUR");

Console.WriteLine(a);                        // Money { Amount = 12.50, Currency = EUR }
Console.WriteLine(a == b);                   // True: synthesized value equality
Console.WriteLine(ReferenceEquals(a, b));    // False: two separate objects
Console.WriteLine(a.GetHashCode() == b.GetHashCode()); // True

var (amount, currency) = a;                  // synthesized Deconstruct
Console.WriteLine($"{amount} {currency}");   // 12.50 EUR

var vip = new Tag { Name = "vip" };          // nominal record: object initializer
Console.WriteLine(vip);                      // Tag { Name = vip }

public record Money(decimal Amount, string Currency);           // positional
public record Tag { public required string Name { get; init; } } // nominal

go deeper

for a junior

Recall the list: init-only properties, a primary constructor, Deconstruct, value equality with == and GetHashCode, and a readable ToString. Say that a record class is still a reference type.

for a middle

Separate what comes from the positional parameters (properties, constructor, Deconstruct) from what every record gets, and know which members you may declare yourself and which the compiler rejects.

for a senior

Talk about what the generated members imply in production: equality and hashing visit every field, ToString prints every public member into logs, and init-only is shallow immutability.

for a principal

Treat records as a contract the compiler writes for you, and decide where value equality and printable state are the right default and where a hand-written class should own identity.

## What a record class is A **record class** is a class declared with the `record` modifier (`record` and `record class` mean the same thing). It is still a **reference type**: a variable holds a reference, assignment copies the reference, and `null` is a valid value. What the modifier changes is how much code the compiler writes for you. It adds a set of **synthesized members** that give the type value-based equality, readable printing and support for copying. A **positional record** declares its data as a parameter list after the type name; a **nominal record** declares ordinary properties in its body. Both are interview staples, because the question "what does that one line expand to?" separates people who have used records from people who have only read about them. ## The members a positional declaration writes For `public record Money(decimal Amount, string Currency);` the compiler produces the following. The right-hand column matters as much as the middle one: some members you may write yourself, and the compiler then skips its own; others are always generated. | Member | What it does | Can you declare it yourself? | |---|---|---| | `Amount`, `Currency` properties | public auto-properties with `get` and `init` | yes, a property of the same name initialized from the parameter | | primary constructor `Money(decimal, string)` | stores the arguments in the properties | no, the parameter list is the constructor | | `Deconstruct(out decimal Amount, out string Currency)` | supports `var (a, c) = money;` | yes | | `Equals(Money? other)` | compares `EqualityContract` and every instance field | yes | | `Equals(object? obj)` | forwards to `Equals(Money?)` | no, error CS0111 | | `GetHashCode()` | combines `EqualityContract` and every field | yes | | `operator ==`, `operator !=` | null-safe calls to `Equals(Money?)` | no, error CS0111 | | `EqualityContract` | returns `typeof(Money)` | yes | | `ToString()` and `PrintMembers(StringBuilder)` | print `Money { Amount = ..., Currency = ... }` | yes | | copy constructor and clone method | used by `with` expressions | the copy constructor yes; the clone method no | The positional properties are **init-only**: they can be set by the constructor, an object initializer or a `with` expression, and nowhere else. Assigning `money.Amount = 5m;` later is a compile error: ```plaintext error CS8852: Init-only property or indexer 'Money.Amount' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. ``` That immutability is **shallow**: an init-only property that holds a `List<T>` cannot be pointed at another list, but the list itself can still be changed. ## Positional and nominal records side by side - **Positional** (`record Money(decimal Amount, string Currency);`): properties, primary constructor and `Deconstruct` come from the parameter list. A primary constructor suppresses the parameterless one, so `new Money()` fails with CS7036. - **Nominal** (`record Tag { public required string Name { get; init; } }`): you write the properties and choose `init`, `set`, `required` or a computed getter. With no constructor declared, the compiler adds a public parameterless one, so you create it with an object initializer. There is **no `Deconstruct`**, because there are no positional parameters to deconstruct. - **Mixed**: a positional record may declare extra properties in its body. They take part in equality and printing, but `Deconstruct` returns only the positional ones. - Either form can override a generated property: `public string Currency { get; } = Currency;` replaces the init-only property with a get-only one. Forget the initializer and the compiler warns with CS8907 that the parameter is unread. ## How the generated equality behaves The equality members are the part interviewers press on: 1. `a == b` first checks whether both references are the same object, then calls `a.Equals(b)` when `a` is not `null`. 2. `Equals(Money?)` returns `false` for `null`, then requires `EqualityContract == other.EqualityContract`, so the two run-time types must match. 3. It then compares every instance field, including the hidden backing fields of the positional properties, with `EqualityComparer<T>.Default` for that field's type. 4. `GetHashCode()` combines the same values, so equal records produce equal hash codes and work as dictionary keys. Two separately constructed `new Money(12.50m, "EUR")` values are therefore `==` and `Equals` each other, while `ReferenceEquals` still reports two distinct objects. ## What to say in an interview - Name the three groups: data members (properties, constructor, `Deconstruct`), equality members, and printing and copy members. - Say that a record class is a reference type, and that `record struct` is the separate value-type form with different defaults. - Point out the rules the compiler enforces: you cannot write `Equals(object)` or the operators yourself, and no member may be named `Clone`. - Mention that init-only is shallow and that a nominal record has no `Deconstruct`.

  • Can you change the accessibility or mutability of one positional property of a record class?
    Yes. Declare a property with the same name in the body and initialize it from the parameter, for example `public string Currency { get; } = Currency;` or `internal decimal Amount { get; init; } = Amount;`. The compiler then skips its own property, and the synthesized `Deconstruct` reads yours. Leave out the initializer and the parameter is never stored; the compiler warns with CS8907 that it is unread.
  • Does a positional record class have a parameterless constructor?
    No. A primary constructor suppresses the implicit parameterless constructor, so `new Money()` fails with CS7036. A nominal record that declares no constructor gets a public parameterless one, which is why it is created with an object initializer. You can add a parameterless constructor to a positional record yourself, but it must chain to the primary constructor with `: this(...)`.

  • Positional record properties have public setters, so code can reassign Amount later.
  • A record is a value type, so assigning it copies the whole object.
  • Two records with the same values are equal only when they are the same instance.
  • A nominal record also gets a Deconstruct method for its properties.
  • You customize record equality by overriding Equals(object).