Since C# 10, how does a with expression behave on a plain struct, a tuple or an anonymous type, compared with a record class?
answer
- C# 10 widened the receiver
- struct: value copy, then assign
- no copy constructor to customize
- anonymous: same generated type
basics
~20 sOn 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.
solid answer
~40 sC# 10 allowed `with` on any struct, which covers tuples, and on anonymous types. For a struct receiver the specification says the receiver is first **copied by value**, then each member in the braces is assigned on the copy in lexical order — there is no clone method, and a constructor you write with a copy-constructor signature is never called, so struct copying **cannot be customized**. The listed members still need a `set` or `init` accessor, or must be mutable fields. For an anonymous type, whose properties are read-only, `with` produces a new instance of the **same** anonymous type with the listed properties replaced. In every case the copy is shallow: a reference-type member, such as a list, is shared.
code
csharp · 23 linesvar s = new S(1);
var t = s with { };
Console.WriteLine(t.X);
var anon = new { Name = "alpha", Tags = new List<string> { "beta" } };
var other = anon with { Name = "bravo" };
other.Tags.Add("trial");
Console.WriteLine(string.Join(",", anon.Tags));
Console.WriteLine(other.GetType() == anon.GetType());
var tuple = (Tenant: "alpha", Timeout: 30);
Console.WriteLine(tuple with { Timeout = 60 });
var p = new Point { X = 1, Y = 2 };
var q = p with { Y = 5 };
Console.WriteLine($"{p.X},{p.Y} {q.X},{q.Y}");
record struct S(int X)
{
public S(S original) : this(original.X + 100) { }
}
struct Point { public int X { get; set; } public int Y { get; init; } }go deeper
Recall that since C# 10 with also works on structs, tuples and anonymous types, and that it still leaves the original alone.
Explain that a struct receiver is copied by value and then assigned, that no copy constructor is involved, and that an anonymous copy keeps the same type.
Know that struct copying cannot be customized, so a struct holding a mutable reference member shares it across every with copy.
Weigh with on large structs as a full copy per call when a team adopts value types for immutable data.
## Receivers beyond records In C# 9, `with` accepted only record classes. **C# 10** widened it: the receiver may be any **struct** (including record structs and value tuples) or an **anonymous type**. With `LangVersion` set to 9 the compiler names both features in its errors: ```plaintext error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. ``` An ordinary class is still rejected (CS8858). ## Structs: copy the value, then assign For a struct receiver, the record-structs specification states the rule directly: the receiver is first **copied**, then each member initializer is processed as an assignment to a field or property of that copy, in lexical order. Copying a struct is the ordinary value copy that assignment performs, so: 1. no method is called to make the copy; 2. the listed members are assigned through their accessors, so a property with a `set` or `init` accessor, or a mutable field, may be listed; 3. the original is unchanged because it was never written. ```csharp var p = new Point { X = 1, Y = 2 }; var q = p with { Y = 5 }; // p is 1,2 ; q is 1,5 struct Point { public int X { get; set; } public int Y { get; init; } } ``` ## No custom copy semantics for structs A record class lets you write your own copy constructor and `with` calls it. A struct has no such hook. Microsoft's documentation says you can't customize the copy semantics for structure types, and the record page adds that the compiler does not synthesize a copy constructor for record structs; you can write a constructor with that signature, but `with` never calls it: ```csharp var s = new S(1); var t = s with { }; // t.X is 1, not 101 record struct S(int X) { public S(S original) : this(original.X + 100) { } } ``` The details of record structs — positional properties, `readonly record struct` — are covered with record structs. ## Tuples `ValueTuple` is a struct with public mutable fields, so `with` works on tuples too, and element names are usable in the braces: ```csharp var tuple = (Tenant: "alpha", Timeout: 30); var longer = tuple with { Timeout = 60 }; // (alpha, 60) ``` ## Anonymous types Anonymous types are classes the compiler generates, with read-only properties and no way to reassign them. `with` gives them nondestructive mutation: `anon with { Name = "bravo" }` creates a new instance of the **same** anonymous type — `other.GetType() == anon.GetType()` is `true` — with `Name` replaced and every other property copied. ## The comparison | Receiver | How the copy is made | Customizable | Result type | |---|---|---|---| | record class | virtual clone method calls the copy constructor | yes, by declaring a copy constructor | the receiver's run-time type | | struct, record struct, tuple | value copy | no | the struct type | | anonymous type | compiler-generated construction of a new instance | no | the same anonymous type | | ordinary class | not allowed | — | CS8858 | ## What stays the same everywhere - **Shallow.** A struct copy copies each field; if a field holds a `List<string>`, both structs share that list. An anonymous type's list property is shared the same way. - **Accessors still apply.** A get-only property cannot be listed, whatever the receiver. - **Nondestructive.** The receiver is not changed. Where value-type copying itself comes from — assignment, parameters, property getters — is covered with copying versus sharing.
- In C#, can a with on a struct list a property that has only a get accessor?No. The struct is copied and then the listed members are assigned as ordinary property or field assignments on the copy, so each must have a `set` or `init` accessor or be a mutable field. A get-only property gives CS0200, exactly as it would for a record.
- In C#, is a with on a large struct expensive?It costs one copy of the whole struct plus the listed assignments, the same as assigning the struct to a new variable and then setting members. For a small struct that is negligible; for a large one it is a full copy of every field on each `with`, which is one more reason to keep structs small.
- with works only on records, never on structs or anonymous types.
- Declaring a copy constructor on a record struct changes what with copies.
- with on an anonymous type returns a different anonymous type.
- A with on a struct deep-copies its list fields.
- with on an anonymous type needs settable properties, so it never compiles.