skip to content

Immutable Data Types

record and record struct generate value equality, ToString, Deconstruct and with-based copies. Interviewers ask records vs classes and what with really copies.

on this pageshow

explore

questions

15

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).
open as a page

In C#, what does settings with { TenantId = "alpha" } return when settings is a record, and does settings change?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A with expression returns a new record of the same run-time type, with every member copied from settings and only TenantId replaced. The original settings object is not modified; both variables now refer to different objects.

open as a page

In C#, why do two Address records with the same city and equal List<string> street lines compare unequal, and how do you fix it?

level: middleimportance: must knowfreq 60%

basics

~10 s

A record's synthesized Equals compares each field with EqualityComparer<T>.Default, and List<T> does not override Equals, so two distinct lists compare by reference. Declare Equals(Address? other) using SequenceEqual and a matching GetHashCode.

open as a page

In C#, why does adding a tag to one tenant's settings record, copied from a baseline with with, change every tenant's Tags list?

level: middleimportance: must knowfreq 62%

basics

~10 s

A with copy copies each field, and a List<string> field holds a reference, so every copy shares one list. Give the copy its own list in the with, or use an immutable collection type.

open as a page

In C#, what does the compiler generate for a `record struct` that a plain `struct` with the same fields does not get?

level: juniorimportance: should knowfreq 35%

basics

~20 s

A C# record struct gets compiler-written IEquatable<T>.Equals, == and !=, a field-based GetHashCode and a member-listing ToString, plus properties and Deconstruct when positional. A plain struct only inherits ValueType's Equals, GetHashCode and type-name ToString, and has no ==.

open as a page

In C#, what does a record's synthesized ToString print, and how do you mask a PaymentCard record's card number in it?

level: middleimportance: should knowfreq 45%

basics

~20 s

It prints the type name and each public instance field and readable property as Name = value inside braces, formatting values with their own ToString. To mask a member, declare PrintMembers(StringBuilder) yourself, or override ToString.

open as a page

In C#, why does `price.Amount = 0m;` compile for `record struct Price(decimal Amount, string Currency)` but fail for a `readonly record struct`?

level: middleimportance: should knowfreq 35%

basics

~20 s

A positional C# record struct generates get and set properties, so they are mutable; a readonly record struct generates get and init, so assigning one after construction is error CS8852, and a with expression makes a changed copy.

open as a page

In C#, what code does the compiler generate for a with expression on a record class, and why may it assign init-only properties?

level: middleimportance: should knowfreq 40%

basics

~20 s

The compiler calls the record's hidden clone method, which runs the copy constructor to copy every field, then assigns the listed members on the new copy. Those assignments count as part of initializing the copy, so init accessors are allowed.

open as a page

Since C# 10, how does a with expression behave on a plain struct, a tuple or an anonymous type, compared with a record class?

level: middleimportance: should knowfreq 30%

basics

~20 s

On a struct or tuple, with copies the value and then assigns the listed members, with no copy constructor to customize. On an anonymous type it builds a new instance of the same type. Both need C# 10.

open as a page

In C#, why is a Customer record never equal to a PremiumCustomer record with the same Id and Name, even through Customer-typed variables?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Every record's synthesized Equals compares EqualityContract, which returns typeof of the record's own type, and a derived record's sealed Equals(Customer?) re-dispatches through an as cast, so different run-time types never compare equal, whatever the variable type.

open as a page

A C# trading app changes `Price` from a `record class` to a `readonly record struct` to cut allocations; what behaviour changes for code that uses it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Price becomes a copied, never-null value: default(Price), new Price() and new arrays skip constructor validation, price == null is always false, inheritance is gone, and object or interface use boxes it. Field-wise value equality is unchanged.

open as a page

In C#, a method takes a TenantSettings record and returns settings with { TimeoutSeconds = 60 }; passed an EnterpriseSettings derived record, what does it return, and what can it change?

level: seniorimportance: should knowfreq 32%

basics

~20 s

It returns an EnterpriseSettings with every derived member, such as Region, copied and TimeoutSeconds set to 60, because the hidden clone method is virtual. The braces may only name members of the compile-time type TenantSettings.

open as a page

Should a C# team model domain entities such as Customer as record classes, or keep records for values like Money and Address?

level: principalimportance: should knowfreq 35%

basics

~20 s

Keep record classes for values whose identity is their data, such as Money, Address, messages and query results, and model entities with identity and a lifecycle as classes, because the generated equality and printing assume the data is the identity.

open as a page

In a C# `record struct`, how do you make equality ignore a string member's case, and which equality members can you not declare?

level: middleimportance: nice to knowfreq 20%

basics

~10 s

Declare a public Equals(R other) and override GetHashCode in the record struct; the synthesized ==, != and Equals(object) then call your Equals. Declaring operator ==, operator != or Equals(object) yourself is error CS0111.

open as a page

In C#, what must a hand-written copy constructor on a record class do so that every with expression deep-copies its Tags list correctly?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

Declare protected TenantSettings(TenantSettings original) (private if sealed), chain to the base copy constructor, clone the list, and assign every other member yourself, because the compiler no longer generates the field-by-field copy.

open as a page