skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

C# with Keyword: Copy Records, Structs, and Avoid Shallow Copies

The C# with keyword copies records, structs, and anonymous types. Learn why the copy is shallow, how it shares a List<T>, and two ways to fix it.

8 min read Updated

The with keyword in C# creates a copy of an object and changes only the properties you name, leaving the original untouched. It works on records, structs (including record struct), and anonymous types, but the copy is shallow: any reference type inside is shared between the original and the copy.

That last part bites people. If a record holds a List<T>, mutating the list through the copy mutates it through the original too. For more traps, see C# record gotchas, or learn how to customize record equality with source generators. For a one-screen version, there’s also a tip on the with expression.

In this post, we’ll look at what with does, which types support it, why the shallow copy surprises people, and two ways to fix it. The samples target .NET 10 and C# 14.

What does the with keyword do in C#?

A with expression takes a source object, the with keyword, and an object initializer that lists only the properties you want to change. Everything you don’t name is copied from the original.

var dune = new Movie(1, "Dune", "max");
var moved = dune with { Service = "netflix" };
Console.WriteLine(dune);
Console.WriteLine(moved);
public record Movie(int Id, string Name, string Service);
Movie { Id = 1, Name = Dune, Service = max }
Movie { Id = 1, Name = Dune, Service = netflix }

The with expression has been available for records since C# 9. Records are meant to be immutable, so with is how you get a “changed” version without mutating anything.

Which types support the with keyword?

Records came first, and C# 10 extended with to structs and anonymous types. Classes that aren’t records can’t use it.

Type with supported since What gets copied
record / record class C# 9 Compiler-generated clone via the copy constructor (shallow)
record struct C# 10 Field-by-field copy of the struct
struct C# 10 Field-by-field copy of the struct
Anonymous type C# 10 New anonymous instance with the same values
Plain class Not supported Compiler error

Here are the non-record cases in one runnable file.

var p = new Point { X = 1, Y = 2 };
var p2 = p with { Y = 5 };
Console.WriteLine($"{p.X},{p.Y} {p2.X},{p2.Y}");
var rs = new Pt(1, 2);
Console.WriteLine(rs with { Y = 9 });
var anon = new { Name = "Khalid", Planet = "Earth" };
var anon2 = anon with { Planet = "Mars" };
Console.WriteLine(anon);
Console.WriteLine(anon2);
public struct Point { public int X; public int Y; }
public record struct Pt(int X, int Y);
1,2 1,5
Pt { X = 1, Y = 9 }
{ Name = Khalid, Planet = Earth }
{ Name = Khalid, Planet = Mars }

Can you use with on a class?

Not on a plain class. This code:

var f = new Foo { N = 1 };
var g = f with { N = 2 };
class Foo { public int N { get; set; } }

fails to compile with:

error CS8858: The receiver type 'Foo' is not a valid record type and is not a struct type.

Make Foo a record and it works. Structs have the same shallow-copy caveat as records: copying a struct copies its fields, and a field that holds a reference still points at the same object.

Why does with share reference types between copies?

Records are specialized classes, so the usual value-type and reference-type rules still apply. A property like Number is an int, so each copy gets its own value. Trying to change it on an existing record is a compiler error, which is the point:

var i = new Item(1);
i.Number = 3;
record Item(int Number);
error CS8852: Init-only property or indexer 'Item.Number' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

Now add a collection. A List<int> is a reference type, so the copy gets the same reference, not a new list.

var item = new Item();
var newItem = item with { };
item.State.Add(1);
newItem.State.Add(2);
Console.WriteLine(item);
Console.WriteLine(newItem);
public record Item(List<int> State)
{
public Item() : this(new List<int>())
{
}
public override string ToString()
{
return $"Item {{ State = {string.Join(", ", State)} }}";
}
}

What do you expect State to be? Don’t peek. You’d be right if you guessed 1, 2 across both instances.

Item { State = 1, 2 }
Item { State = 1, 2 }

That’s a shallow copy. The with expression copies each field, and for a reference type, the field value is the reference. Both records point to one list. It’s fine if nobody mutates the data, and a bug factory if somebody does.

How do we solve it? There are two ways, plus a third option that avoids the problem entirely.

How do you avoid shared state when using with?

Option 1: replace the reference in the with initializer

Be aware of every reference type in the record, and swap in a new value as part of the with.

var item = new Item();
var newItem = item with { State = item.State.Append(2).ToList() };
item.State.Add(1);
Console.WriteLine(item);
Console.WriteLine(newItem);
public record Item(List<int> State)
{
public Item() : this(new List<int>())
{
}
public override string ToString()
{
return $"Item {{ State = {string.Join(", ", State)} }}";
}
}
Item { State = 1 }
Item { State = 2 }

That works, but every caller has to remember to do it.

Option 2: write a copy constructor

A copy constructor takes an instance of the record’s own type and lets you decide how each member is copied. When you write a with expression, the compiler generates a hidden <Clone>$ method on the record, and that method calls the copy constructor. If you define one, yours is used instead of the synthesized one.

var item = new Item();
var newItem = item with { };
item.State.Add(1);
newItem.State.Add(2);
Console.WriteLine(item);
Console.WriteLine(newItem);
public record Item(List<int> State)
{
public Item() : this(new List<int>())
{
}
// copy constructor
protected Item(Item oldItem)
{
State = new List<int>(oldItem.State);
}
public override string ToString()
{
return $"Item {{ State = {string.Join(", ", State)} }}";
}
}
Item { State = 1 }
Item { State = 2 }

Two rules the compiler enforces. First, in a non-sealed record, the copy constructor must be protected or public, otherwise, you get this:

error CS8878: A copy constructor 'Item.Item(Item)' must be public or protected because the record is not sealed.

Second, a sealed record can use a private copy constructor, since nothing can derive from it. The compiler still calls it for with:

var s = new Item(new List<int> { 1 });
var s2 = s with { };
Console.WriteLine(ReferenceEquals(s.State, s2.State));
public sealed record Item(List<int> State)
{
private Item(Item other)
{
State = new List<int>(other.State);
}
}
False

Notice the copy constructor doesn’t chain to this(...) even though Item is a positional record. A user-defined copy constructor is exempt from that rule, so assigning State directly is fine.

Option 3: use immutable collections

Better still, don’t hold a mutable collection at all. IReadOnlyList<T> looks like the answer, but it’s only a read-only view. The list underneath is still shared, and whoever owns the original List<T> can keep changing it:

var l = new List<int> { 1 };
var r = new Ro(l);
var r2 = r with { };
l.Add(2);
Console.WriteLine(string.Join(",", r2.Items));
public record Ro(IReadOnlyList<int> Items);
1,2

ImmutableArray<T> or ImmutableList<T> from System.Collections.Immutable can’t be changed after creation, so sharing them between copies is harmless. “Changing” the collection returns a new one, which pairs well with with:

using System.Collections.Immutable;
var c = new Cart(1, ImmutableArray.Create(1));
var d = c with { Items = c.Items.Add(2) };
Console.WriteLine(c);
Console.WriteLine(d);
public record Cart(int Id, ImmutableArray<int> Items)
{
public override string ToString() => $"Cart {{ Items = {string.Join(", ", Items)} }}";
}
Cart { Items = 1 }
Cart { Items = 1, 2 }

Frequently asked questions about the C# with keyword

Is the with expression a deep copy?

No. It’s a shallow copy. Value-type members are copied, and reference-type members are copied as references, so both objects point at the same underlying instance. For a deep copy, replace those members in the with initializer or write a copy constructor that clones them.

Can you use with on a class?

Only if the class is a record. A plain class fails with error CS8858: “The receiver type ‘Foo’ is not a valid record type and is not a struct type.”

Can you use with on a struct?

Yes, since C# 10. It works on struct, record struct, and anonymous types. The struct is copied and then the named members are set.

Does with call the constructor?

For records, it calls the copy constructor, through a compiler-generated <Clone>$ method, and then runs your object initializer on the result. The positional constructor isn’t called. For structs, the value is copied directly.

How do I deep copy a record?

Write a copy constructor that clones each reference-type member, or build the record from immutable types like ImmutableArray<T> so there’s nothing to clone. For nested records, with on each level of the nesting works too.

Conclusion

The with keyword is a clean way to get a changed copy of a record, struct, or anonymous type, but it only copies one level. Under the hood, a record is a specialized class, so the reference-type rules still apply. My recommendation: reach for ImmutableArray<T> first, and add a copy constructor when a record has to hold something mutable. Either way, decide on purpose what gets copied.

For a quick refresher on records next to classes and structs, see my C# cheat sheet. If the List<T> in these samples made you curious about type parameters, C# generics explained covers them.

Thanks for reading, and thank you for sharing this post with friends and colleagues. Cheers :)

Comments

Related Posts