In C#, what code does the compiler generate for a with expression on a record class, and why may it assign init-only properties?
answer
- two steps, in a fixed order
- hidden virtual clone method
- copy constructor copies fields only
- initializers do not run again
basics
~20 sThe 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.
solid answer
~40 sFor a record class the compiler synthesizes a **copy constructor** (protected, or private when the record is sealed) and a public **clone method**, virtual unless the record is sealed, with a compiler-reserved name (`<Clone>$`). A `with` expression calls the clone method, which returns `new R(this)`; the copy constructor copies every instance field and runs **no field or property initializers**. Then each `member = value` in the braces is assigned on the copy in lexical order, through the member's `set` or `init` accessor — so `init` validation runs for listed members only. `init` is legal there because the copy is still being initialized; outside an initializer the same assignment fails with CS8852. Consequence: a property computed in an initializer is copied, not recomputed, so it goes stale.
code
csharp · 14 linesvar eu = new TenantSettings("alpha", "eu-west");
var us = eu with { Region = "us-east" };
Console.WriteLine(us.Region);
Console.WriteLine(us.CacheKey);
Console.WriteLine(us.CacheKeyOnRead);
Console.WriteLine(us.SnapshotId == eu.SnapshotId);
record TenantSettings(string TenantId, string Region)
{
public Guid SnapshotId { get; } = Guid.NewGuid();
public string CacheKey { get; } = $"{TenantId}:{Region}";
public string CacheKeyOnRead => $"{TenantId}:{Region}";
}go deeper
Recall that with copies the whole record first and then assigns the members you listed on the copy.
Walk through the clone method, the copy constructor that copies fields without initializers, the lexical-order assignments, and why init is legal there (CS8852 elsewhere).
Use the lowering to explain stale cached properties and copied identifiers in production records, and move validation into init accessors.
Set a rule that records compute derived values on read and validate in accessors, because every with silently skips constructors and initializers.
## The two generated members When you declare a `record` (a record class), the compiler adds two copying members: - a **copy constructor** — a constructor whose single parameter is the record's own type, `protected TenantSettings(TenantSettings original)`. It is `protected` in a record that can be derived from and `private` in a `sealed` record. Reflection on a positional record shows it next to the primary constructor. - a **clone method** — public, parameterless, virtual (unless the record is sealed or abstract), with a compiler-reserved name, `<Clone>$` in the emitted metadata. Its body is `return new TenantSettings(this);`. You cannot call it by name, override it, or declare any member called `Clone` in a record (CS8859). ## What `with` lowers to `var us = eu with { Region = "us-east" };` becomes, in effect: 1. `var tmp = eu.<Clone>$();` — a virtual call, so the run-time type's clone runs. 2. `tmp` is converted to the receiver's compile-time type. 3. For each entry in the braces, in the order written: `tmp.Region = "us-east";` through the property's accessor. 4. The expression's value is `tmp`. The copy constructor, per the records specification, first calls the base copy constructor (or `object()`), then **copies the values of all instance fields** declared in the record — including the hidden backing fields of auto-properties. It does **not** run field or property initializers, and it does not run the primary constructor. ## Why `init` accessors are allowed An `init` accessor may be called only while an object is being initialized: in an object initializer, on `this` or `base` in a constructor, or in another `init` accessor. A plain assignment after construction is rejected: ```plaintext error CS8852: Init-only property or indexer 'TenantSettings.Region' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. ``` The brace list of a `with` expression is treated like an object initializer on the brand-new copy, so `init` accessors are callable there. That is why positional records, whose properties are `init`-only, can be "changed" only through `with` or a new constructor call. ## Consequences you can observe | Behaviour | Why | |---|---| | A listed member's `init` validation runs | step 3 calls the accessor | | An unlisted member's `init` logic does not run | the copy constructor copies fields, it does not call accessors | | A property initialized from other members keeps the old value | initializers are not re-run on the copy | | An initializer like `= Guid.NewGuid()` is copied, not regenerated | same reason — the copy gets the field value | The documented trap is a cached computed property: ```csharp record TenantSettings(string TenantId, string Region) { public string CacheKey { get; } = $"{TenantId}:{Region}"; public string CacheKeyOnRead => $"{TenantId}:{Region}"; } ``` After `eu with { Region = "us-east" }`, `CacheKey` still reads `alpha:eu-west` while `CacheKeyOnRead` reads `alpha:us-east`. Microsoft's guidance is to compute such values on access rather than store them at construction. ## How to write records that survive `with` - Compute derived values in a getter (`=>`), not in an initializer or constructor. - Put validation in the `init` accessor of the property it guards, so a `with` that sets the property still validates it; a check that only lives in a constructor is skipped by every copy. - Treat any identity-like value assigned in an initializer as "copied by `with`"; if each copy needs a new one, list it in the `with`.
- In C#, does a with expression need to set the record's required members again?No. `required` obliges the creator of a new object to set the member in an object initializer, but a `with` copy starts from the clone, which already holds every value. Only the members you list are assigned, and the compiler does not ask for required ones.
- In C#, where should validation live so that with cannot bypass it?In the `init` accessor of the property it guards. A `with` assigns listed members through their accessors, so the check runs whenever a copy changes that property. A check placed only in a constructor runs at `new` and never during a `with`, because the copy constructor copies fields without calling it.
- In C#, can you call a record's clone method directly?No. Its name, `<Clone>$`, is not a valid C# identifier, so source code cannot refer to it, and declaring any member named `Clone` in a record is error CS8859. The only way to invoke it is a `with` expression; to customize copying you write the copy constructor instead.
- with calls the primary constructor again with the changed arguments.
- with uses reflection to copy the properties one by one at run time.
- Field initializers run again on the copy, so cached values are recomputed.
- with writes backing fields directly, so init accessors never run.
- A record's Clone method can be overridden to customize with.