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?
answer
- replaces the synthesized one entirely
- public or protected unless sealed
- chain to the base copy constructor
- copy every member yourself
basics
~10 sDeclare 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.
solid answer
~50 sDeclaring a constructor whose single parameter is the record's own type **replaces** the synthesized copy constructor, and the hidden clone method — so every `with` — calls yours. The compiler enforces its shape: it must be `public` or `protected` unless the record is `sealed` — `internal` and `protected internal` are rejected too (CS8878), and in a derived record it must chain to a base copy constructor, `: base(original)` (CS8868). Then it must copy **every** member: anything you forget is left at its default — a forgotten `int` silently becomes `0`, while nullable analysis only warns (CS8618) about a forgotten non-nullable reference. So the body is `TenantId = original.TenantId; TimeoutSeconds = original.TimeoutSeconds; Tags = [.. original.Tags];`. Derived records' synthesized copy constructors call it, so they get the cloned list too. Struct copies cannot be customized this way.
code
csharp · 16 linesvar baseline = new TenantSettings("default", 30, ["beta"]);
var alpha = baseline with { TenantId = "alpha" };
alpha.Tags.Add("priority-support");
Console.WriteLine(string.Join(",", baseline.Tags));
Console.WriteLine(string.Join(",", alpha.Tags));
Console.WriteLine(alpha.TimeoutSeconds);
record TenantSettings(string TenantId, int TimeoutSeconds, List<string> Tags)
{
protected TenantSettings(TenantSettings original)
{
TenantId = original.TenantId;
Tags = new List<string>(original.Tags);
}
}go deeper
Recall that a record can declare its own copy constructor and that with then uses it.
Explain the accessibility rule (CS8878), the base chaining rule (CS8868) and that the hand-written constructor replaces the generated field copy.
Catch the silent defaults from forgotten value-type members, test copies for independence, and know struct copies cannot be customized.
Weigh a custom copy constructor's maintenance cost against making members immutable so that shallow copies are already safe.
## Why write one A record's synthesized **copy constructor** copies every instance field, so a `List<string>` member ends up shared between a record and every `with` copy of it. Fixing that at each call site (`with { Tags = [.. s.Tags] }`) relies on everyone remembering. Declaring the copy constructor yourself fixes it once: the hidden clone method that every `with` calls runs `new TenantSettings(this)`, and that is now your code. Microsoft's documentation shows exactly this use: an explicit copy constructor that copies list items instead of the list reference. ## The rules the compiler enforces | Rule | Diagnostic when broken | |---|---| | A copy constructor in a record that is not `sealed` must be `public` or `protected` | CS8878: "A copy constructor 'A.A(A)' must be public or protected because the record is not sealed." | | In a derived record it must call a base copy constructor | CS8868: "A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object." | | No member may be named `Clone` | CS8859: "Members named 'Clone' are disallowed in records." | The accessibility rule is strict: `internal`, `protected internal` and `private protected` are all rejected with CS8878 in an unsealed record, even though two of them include protected access. In a `sealed` record a `private` copy constructor is fine, and is what the compiler would have generated. ## It replaces the whole copy The synthesized copy constructor is generated **only** when you do not declare one. Once you write it, nothing copies fields for you. Members you do not assign are left at their defaults: ```csharp record TenantSettings(string TenantId, int TimeoutSeconds, List<string> Tags) { protected TenantSettings(TenantSettings original) { TenantId = original.TenantId; Tags = new List<string>(original.Tags); // TimeoutSeconds forgotten: every with copy now has 0 } } ``` With nullable reference types enabled, forgetting `TenantId` produces warning CS8618 ("Non-nullable property 'TenantId' must contain a non-null value when exiting constructor"), but forgetting `TimeoutSeconds` produces nothing — an `int` defaulting to `0` is not a nullable violation. The correct body assigns everything: 1. every positional property and every other property with a backing field; 2. every explicitly declared field; 3. the cloned collections — `Tags = [.. original.Tags]` or `new List<string>(original.Tags)`. Field and property initializers do not run in a copy constructor, so you cannot rely on them to fill gaps. ## Inheritance - A derived record **without** its own copy constructor gets a synthesized one that calls `base(original)` first, so your base copy constructor — and its list clone — runs for derived copies too. - A derived record **with** its own copy constructor must write `: base(original)`; calling the base's primary constructor instead is CS8868. - `with` through a base-typed variable still copies the run-time type, through the derived constructor chain. ## What this does not cover - **Record structs and other structs.** A struct `with` is a value copy. The compiler does not synthesize a copy constructor for record structs, and one you declare is never called by `with`, so struct copying cannot be customized. - **Deep copies of nested records.** Cloning `Tags` copies the list, not objects inside it; strings are immutable, so that is enough here, but a list of mutable objects needs its elements copied too. - **Maintenance.** Every member added to the record must be added to the copy constructor. An immutable collection type for `Tags` avoids writing one at all, because sharing an immutable collection is safe; that choice is covered with the collections material. ## Review checklist - Accessibility: `protected` (or `public`), `private` only when `sealed`. - Chains to `base(original)` in a derived record. - Assigns every member, including value types the compiler will not warn about. - A test copies a record with `with`, mutates the copy's collection, and asserts the original is unchanged.
- In C#, does a derived record that declares no copy constructor still get the base record's custom list clone?Yes. Its synthesized copy constructor calls the base copy constructor first and then copies the derived fields, so the base's clone of `Tags` runs for every `with` on the derived record, through any variable type.
- In C#, can you make with deep-copy a record struct by declaring a copy constructor?No. `with` on any struct copies the value and then assigns the listed members; it never calls a constructor. A constructor with the copy signature compiles on a record struct but is ignored by `with`, so a record struct holding a list shares it across copies.
- In C#, why does forgetting TimeoutSeconds in a custom copy constructor produce no warning?Because nothing is wrong by the compiler's rules: an `int` left at `0` is a valid value. Nullable analysis warns (CS8618) only about non-nullable reference members left null. Only a test that compares a `with` copy's unlisted members to the original catches it.
- A custom copy constructor only needs to copy the list; the rest is copied automatically.
- The copy constructor can be private in a record that is not sealed.
- A derived copy constructor may call the base primary constructor instead.
- Declaring S(S original) on a record struct customizes with.
- Overriding the record's Clone method is the way to customize with.