Prototype intent, shallow vs deep copy, MemberwiseClone semantics, ICloneable's ambiguity, records and with (shallow copy constructor), deep-copy options, JsonSerializerOptions and HttpRequestMessage cloning, and EF Core PropertyValues.Clone.
Prototype creates new objects by copying a configured instance instead of building from scratch. It's useful when setup is expensive or when you want variations of a template.
MemberwiseClone() makes a protected, shallow, field-by-field copy without running constructors.ICloneable is discouraged: Clone() returns object and doesn't say whether the copy is deep or shallow.record with uses a compiler-generated copy constructor, so it's shallow. A List<T> property is shared, and changing the copy's list changes the original's too.The modern answer is usually immutability: immutable members make shallow copies safe and cheap. The trade-off is that you need a hand-written copy constructor whenever a mutable reference has to be deep-copied.
"Prototype means creating an object by copying an existing, already-configured one rather than constructing it. It's useful when construction is expensive, or when you keep a template and stamp out variations, like a default quote or a base set of serializer options. The whole pattern hinges on what 'copy' means. A shallow copy duplicates the fields of the top object, so value types are copied but reference-type fields still point to the same objects. A deep copy duplicates the whole graph.
object.MemberwiseClone()is the built-in shallow copy. It's protected, it copies fields bit for bit, and it doesn't run any constructor.ICloneableis the interface everyone expects to use, but the design guidelines say not to, becauseClone()returnsobjectand gives callers no way to know whether they got a deep or a shallow copy.In modern C# the prototype most people use without noticing is the record
withexpression. It calls a compiler-generated copy constructor, which is shallow. If the record has aList<OrderLine>,quote with { CustomerId = x }shares that list, and adding a line to the copy adds it to the original. The framework has explicit copy APIs too.new JsonSerializerOptions(existing)copies options, which matters because options become read-only once they're used. AnHttpRequestMessagecan only be sent once, so retry handlers have to clone it. EF Core offersentry.CurrentValues.Clone()andToObject()for snapshotting entity values.The mistake I see is caching a template object and handing out
withcopies of it, then mutating a collection on the copy. That leaks data between users. My fix is usually immutability: give the recordImmutableArray<T>or a fresh read-only list, so a shallow copy is safe. Where a mutable member is unavoidable, I write a protected copy constructor that deep-copies it. Shallow copies are only safe for immutable data."
| Shallow copy | Deep copy | |
|---|---|---|
| Value-type fields | Copied | Copied |
| Reference fields | Same object shared | New copies, recursively |
| Cost | O(fields) | O(graph size) |
| Cycles | No issue | Must be detected |
| C# tools | MemberwiseClone, record with |
Copy constructors, serialisation round trip |
| Mechanism | Depth | Constructors run | Notes |
|---|---|---|---|
MemberwiseClone() |
Shallow | No | Protected; call from inside the type |
Record with |
Shallow | Copy constructor only | Override with your own protected R(R original) |
ICloneable.Clone() |
Unspecified | Implementation-defined | Avoid in public APIs |
| Hand-written copy constructor | Whatever you choose | Yes | Explicit and fast; must be maintained |
JsonSerializer round trip |
Deep (public data only) | Yes | Slow, loses private state, cycles need ReferenceHandler.Preserve |
BinaryFormatter |
Deep | No | Removed in .NET 9 (insecure); don't use |
A quoting API cached a default Quote record per product and returned defaultQuote with { CustomerId = id }. The record held a List<QuoteLine>, and a promotion step appended a discount line to each copy, so every request added another line to the shared cached list. Within an hour, quotes showed dozens of discount lines and memory grew by about 300 MB. Switching the property to ImmutableArray<QuoteLine> and adding a line with quote with { Lines = quote.Lines.Add(line) } fixed it with no measurable latency change.
Checks the candidate's grasp of reference semantics and copying, and whether they know modern C# copy behaviour.
Green flags
MemberwiseClone is protected, shallow and skips constructors.ICloneable is discouraged.with is shallow and proposes immutability or a copy constructor.Red flags
with or MemberwiseClone deep-copies.BinaryFormatter for deep copies.Client βββΆ Β«interfaceΒ» IPrototype<T>
+ Clone(): T
β²
ConcretePrototype
Clone() => copy of this
Registry (optional): name βββΆ prototype instance
client: registry["standard-quote"].Clone()
A prototype registry (a dictionary of named templates) is the common real-world shape: clone a template, then customise.
MemberwiseClone actually doesThe runtime allocates a new object of the same exact runtime type and copies the field memory, including the object header's method table pointer but not the sync block. Value-type fields, including structs, are copied by value; reference fields are copied as references. No constructor, field initialiser or init accessor runs. Because it is protected, only the type itself or a derived type can call it, typically inside a public Clone() or DeepClone() method.
withFor record Quote(Guid CustomerId, List<QuoteLine> Lines), the compiler generates:
<Clone>$() method that callsprotected Quote(Quote original) copy constructor that copies every field.q with { CustomerId = x } means: call <Clone>$(), then run the init accessors for the listed properties on the copy. You can declare your own copy constructor to deep-copy:
protected Quote(Quote original)
{
CustomerId = original.CustomerId;
Lines = [.. original.Lines]; // new list
}
In derived records, with preserves the runtime type because <Clone>$ is virtual.
ICloneable is discouragedIt was in .NET 1.0 before generics. object Clone() forces casts, and the contract never specified depth, so ArrayList.Clone is shallow while user types might be deep. Callers can't rely on either. The Framework Design Guidelines say not to implement ICloneable and not to use it in public APIs. Instead, define a well-named, typed method like DeepCopy() or CopyWith(...), or use records.
| Strategy | Speed | Correctness risks |
|---|---|---|
| Copy constructors | Fast | Forgetting a new field (cover with a test using reflection) |
| Serialise and deserialise (System.Text.Json) | Slow (microseconds to milliseconds) | Private fields lost, polymorphism needs configuration, cycles |
| Expression-tree or source-generated cloners | Fast | Third-party dependency, edge cases with readonly fields |
| Immutable data, no copy needed | Fastest | Requires immutable design |
Immutable collections (ImmutableList<T>, ImmutableArray<T>) use structural sharing or cheap copies, so "copy with one change" doesn't duplicate the whole structure.
JsonSerializerOptions: has a copy constructor; an instance becomes read-only after first use (or MakeReadOnly()), so you copy to customise.HttpRequestMessage: can be sent only once ("The request message was already sent"). A retrying DelegatingHandler must build a new request, copying headers and buffering the content.context.Entry(entity).CurrentValues.Clone() gives a detached PropertyValues snapshot; .ToObject() materialises an entity instance. Useful for "duplicate this record" features, after clearing the key.List<int> property, copy it with with, add to the copy's list and print both.JsonSerializer round trip for a 50-field object with BenchmarkDotNet [MemoryDiagnoser].The shallow-copy trap with records, and two fixes:
namespace Quotes;
using System.Collections.Immutable;
public sealed record QuoteLine(string Description, decimal Amount);
// BUG: with copies the reference to the same List
public sealed record MutableQuote(Guid CustomerId, List<QuoteLine> Lines);
public static class Demo
{
public static void ShowBug()
{
var template = new MutableQuote(Guid.Empty, [new("Base fee", 100m)]);
MutableQuote forAlice = template with { CustomerId = Guid.NewGuid() };
forAlice.Lines.Add(new("Loyalty discount", -10m));
Console.WriteLine(template.Lines.Count); // 2: the cached template was modified
}
}
// FIX 1: immutable members make shallow copies safe
public sealed record Quote(Guid CustomerId, ImmutableArray<QuoteLine> Lines)
{
public Quote AddLine(QuoteLine line) => this with { Lines = Lines.Add(line) }; // new array, template untouched
}
// FIX 2: when a member must stay mutable, deep-copy in a custom copy constructor
public record Basket(Guid CustomerId)
{
public List<QuoteLine> Items { get; init; } = [];
protected Basket(Basket original) // used by `with`
{
CustomerId = original.CustomerId;
Items = [.. original.Items]; // new list; QuoteLine is an immutable record, so sharing items is fine
}
}
// Framework prototypes
namespace Quotes;
using System.Text.Json;
public static class JsonDefaults
{
public static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web);
// Options become read-only after first use, so customise a copy instead of mutating the shared instance
public static JsonSerializerOptions WithIndent() => new(Web) { WriteIndented = true };
}
with produces an independent copy. Why it is wrong: It's shallow; mutable reference members such as List<T> are shared with the original. Instead: Use immutable members or a custom copy constructor that copies them.ICloneable in a public API. Why it is wrong: Callers can't tell if Clone() is deep or shallow, and they must cast from object. Instead: A typed, well-named method (DeepCopy()), a record, or a copy constructor.MemberwiseClone on a type with a mutable collection and calling it a copy. Why it is wrong: Both instances share the collection, so changes leak. Instead: Clone, then replace mutable reference fields with copies.JsonSerializer in a hot path. Why it is wrong: It allocates heavily, is orders of magnitude slower, and silently drops private state. Instead: Copy constructors or immutable data.BinaryFormatter-based clone helper from old code. Why it is wrong: BinaryFormatter is insecure and its implementation was removed in .NET 9; it throws. Instead: Explicit copies or a safe serialiser.CurrentValues.Clone().ToObject(), reset the key, then Add.JsonSerializerOptions after use. Why it is wrong: It throws InvalidOperationException once the options are read-only. Instead: Copy with new JsonSerializerOptions(existing).In modern C#, Prototype has mostly turned into a question about immutability. If the data is immutable, shallow copies are free and safe, and with becomes a perfect prototype. If it's mutable, every copy is a potential shared-state bug. So my default is immutable records with immutable collections, and explicit copy constructors where mutability is justified.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Record with over immutable members |
Templates, options, value objects | Near zero | Mutable members present |
| Custom copy constructor | A few mutable members to deep-copy | Must be maintained with new fields | Large evolving graphs |
| Serialisation round trip | Rare deep copies of DTOs | Slow, lossy | Hot paths, private state |
| Re-construct from a factory | Construction is cheap | None | Construction is expensive (the reason to clone) |
To prove a copy is independent I write a test that mutates every mutable member of the copy and asserts the original is unchanged. To prove the copy is cheap enough, I benchmark with [MemoryDiagnoser] and check bytes allocated per copy.
A record is a type whose identity is its data. public record Money(decimal Amount, string Currency); makes the compiler generate init-only properties, a constructor, Deconstruct, value-based Equals/GetHashCode/==, a readable ToString, and a hidden clone method used by with expressions for non-destructive mutation. record (or record class, C# 9) is a reference type; record struct (C# 10) is a value type whose positional properties are mutable unless you write readonly record struct. Equality includes an EqualityContract so a base and derived record are never equal. Watch out: with is a shallow copy, collection members compare by reference, and records are a poor fit for EF Core entities, which need identity-based equality.
Prefer immutable types for values, messages, configuration, cache entries and anything shared across threads: an object that cannot change is automatically thread-safe, safe to cache and share, safe as a dictionary key, and easier to reason about. C# gives you readonly fields, init and get-only properties, records with with, readonly struct, ImmutableArray<T>/ImmutableList<T> and FrozenDictionary/FrozenSet for read-mostly data. Remember that read-only is not immutable: IReadOnlyList<T> over a List<T> can still change underneath. Keep mutability where it is natural and contained: entities whose state changes through methods that guard invariants, builders, and hot loops where allocating new objects would cost too much.
How to tell it (STAR)
**S:** At [company] our quoting API started returning quotes with dozens of duplicate discount lines, and memory was climbing. **T:** I needed to stop the bad quotes and find why a cached template was changing. **A:** I reproduced it with two requests in a test. The cached default quote was a record with a `List` of lines, and `with` copies are shallow, so the promotion step was appending to the shared cached list. I cleared the cache and switched off the promotion within [30 minutes], then made the lines an `ImmutableArray` so customising a quote always creates a new array. **R:** Quotes were correct again, memory flattened at [~400 MB], and the new test plus an 'immutable cache entries' guideline has prevented [two] similar bugs since.
Last updated 18 Nov 2026.