📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Prototype pattern? Explain shallow versus deep copies, how MemberwiseClone works, why ICloneable is discouraged, and why a record's with expression can still surprise you.

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.

Mid-Level Theory Intermediate cloning csharp design-patterns immutability prototype records

🎯 Key points

  • Prototype creates new objects by copying a configured existing instance instead of constructing from scratch; it pays off when setup is expensive or you stamp out variations of a template
  • Shallow copy copies the values of top-level fields: value types are duplicated, but reference fields still point to the same objects, which stay shared. Deep copy duplicates the whole object graph
  • object.MemberwiseClone() is protected, makes a shallow field-by-field copy and does not run constructors
  • ICloneable is discouraged by the Framework Design Guidelines: Clone() returns object and doesn't say whether the copy is deep or shallow
  • Record with expressions call a compiler-generated copy constructor: shallow, so List<T> and mutable reference properties are shared between original and copy
  • Fix with immutable members (ImmutableArray, fresh read-only lists) or a hand-written protected copy constructor that deep-copies; shallow copy of immutable data is O(fields) and safe in hot paths
  • Deep copy options: explicit copy constructors (fast, explicit), System.Text.Json round trip (slow and allocation-heavy, public members only, cycles need ReferenceHandler); BinaryFormatter's implementation was removed in .NET 9
  • Framework examples: new JsonSerializerOptions(existing) copy constructor, cloning HttpRequestMessage for retries, EF Core PropertyValues.Clone()/ToObject()

⏱ 30-second answer

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.

  • A shallow copy duplicates top-level fields, but reference fields still point to the same objects. A deep copy duplicates the whole graph.
  • 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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. ICloneable is the interface everyone expects to use, but the design guidelines say not to, because Clone() returns object and 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 with expression. It calls a compiler-generated copy constructor, which is shallow. If the record has a List<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. An HttpRequestMessage can only be sent once, so retry handlers have to clone it. EF Core offers entry.CurrentValues.Clone() and ToObject() for snapshotting entity values.

The mistake I see is caching a template object and handing out with copies of it, then mutating a collection on the copy. That leaks data between users. My fix is usually immutability: give the record ImmutableArray<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 vs deep

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

Copy mechanisms in .NET

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

Production example

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.

πŸ” What the interviewer is checking

Checks the candidate's grasp of reference semantics and copying, and whether they know modern C# copy behaviour.

Green flags

  • Explains shallow vs deep precisely with reference fields.
  • Knows MemberwiseClone is protected, shallow and skips constructors.
  • Knows why ICloneable is discouraged.
  • Recognises that with is shallow and proposes immutability or a copy constructor.

Red flags

  • Believes with or MemberwiseClone deep-copies.
  • Suggests BinaryFormatter for deep copies.
  • Can't say when cloning beats constructing.

πŸ“š Learn in depth

1. Structure

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.

2. What MemberwiseClone actually does

The 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.

3. Records and with

For record Quote(Guid CustomerId, List<QuoteLine> Lines), the compiler generates:

  • a hidden virtual <Clone>$() method that calls
  • a protected 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.

4. Why ICloneable is discouraged

It 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.

5. Deep copy strategies

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.

6. Framework prototypes

  • 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.
  • EF Core: 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.

Try it yourself

  1. Create a record with a List<int> property, copy it with with, add to the copy's list and print both.
  2. Add a custom copy constructor that copies the list and repeat.
  3. Benchmark copy constructor vs JsonSerializer round trip for a 50-field object with BenchmarkDotNet [MemoryDiagnoser].
  4. Write a test that fails if a new field is added to a class but not copied by its copy constructor (compare all fields via reflection).

πŸ’» Code

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 };
}

⚠ Common mistakes

  • Mistake: Assuming 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.
  • Mistake: Implementing 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.
  • Mistake: Using 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.
  • Mistake: Deep-copying through 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.
  • Mistake: Reusing a 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.
  • Mistake: Cloning an EF Core entity including its key and attaching it. Why it is wrong: The context throws because another instance with the same key is already tracked, or you overwrite the original row. Instead: CurrentValues.Clone().ToObject(), reset the key, then Add.
  • Mistake: Mutating a shared JsonSerializerOptions after use. Why it is wrong: It throws InvalidOperationException once the options are read-only. Instead: Copy with new JsonSerializerOptions(existing).

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions record with expressions Why: Checks what the compiler generates for records, including the copy constructor
    How to answer

    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.

  2. When: Candidate proposes immutable members as the fix Why: Checks immutability trade-offs that make shallow copies safe
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Cached quote template grew a new discount line on every request
Situation
A quoting API on .NET [10] for an [insurance] product, serving [~50] quotes per second. Default quotes were cached per product as records and customised with `with` for each customer.
Signals
Customers reported quotes with dozens of 'Loyalty discount' lines; quote totals went negative for some; `dotnet-counters` showed the GC heap growing by [~300 MB] an hour.
Investigation
Reproduced with two consecutive requests in a test: the second quote had two discount lines. Inspected the record: `List<QuoteLine> Lines`. The `with` copy shared the list, and the promotion step appended to it, modifying the cached template. A memory dump (`dumpheap -stat`) showed one `List<QuoteLine>` with [~180,000] items rooted by the cache.
Resolution
Immediate: cleared the cache and disabled the promotion step with a feature flag. Real fix: changed `Lines` to `ImmutableArray<QuoteLine>` and added `AddLine` returning `this with { Lines = Lines.Add(line) }`, so templates can't be modified.
Prevention
Added a test that customises a template and asserts it's unchanged; added a team guideline that cached objects must be immutable; added a review checklist item for mutable collections in records.

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.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me