Memento intent and roles (originator, memento, caretaker), opaque snapshots via a private nested type behind a marker interface, immutable records and with-expressions as free snapshots, structural sharing with ImmutableList<T>, memory costs and capping history, Memento vs Command undo, persisting and versioning snapshots, and snapshots in event sourcing.
Memento captures an object's internal state as a snapshot so you can restore it later, without exposing that state. The originator creates and restores snapshots; the caretaker (an undo stack) stores them but can't look inside.
In C# the cleanest way is a private nested snapshot record behind a public marker interface, so only the originator can read it.
Immutability makes it cheap: with immutable records, the previous instance is the snapshot, and ImmutableList<T> shares structure, so snapshots don't copy everything.
Compared with Command-based undo, Memento stores whole states (simple, but memory-hungry) while Command stores operations and their inverses (compact, but each needs a correct Undo). In event sourcing, periodic snapshots are mementos that speed up rebuilding state from events.
The trade-off is memory per snapshot against simplicity of restore.
"Memento is how you take a snapshot of an object so you can put it back later, without making its internals public. There are three roles. The originator, say a
FormDesignin a form builder, knows how to save its state into a memento and restore from one. The caretaker, an undo history, keeps a stack of mementos but treats them as opaque tokens. And the memento itself holds the state. The encapsulation part matters: if the history could read and edit snapshots, you've effectively made every private field public.In C#, I get that by making the snapshot a private nested record inside the originator, implementing a public marker interface like
IFormMemento. The caretaker can holdIFormMementovalues but can't see the fields; onlyFormDesign.Restorecan cast it back. What makes this practical is immutability. If the state is held in immutable records andImmutableList<T>, taking a snapshot is just keeping a reference to the current values; nothing gets copied, and adding a field to a 5,000-field list creates a handful of new tree nodes, not a new list. If the whole originator is an immutable record, the previous instance is the memento, and awithexpression gives you the next state. I keep in mind thatwithis shallow, so anything mutable inside it is shared.The mistake I see is deep-copying a large object graph on every keystroke 'for undo', which is how an editor ends up using gigabytes. I cap history, coalesce rapid edits into one entry, and use structural sharing. I'd also compare it with Command-based undo: commands store the operation and its inverse, which is compact, but every command needs a correct
Undo, and bugs there are subtle. Event sourcing is related but inverted: you store the events and rebuild state; snapshots every few hundred events are mementos that make loading fast. Memento trades memory for simplicity: restoring a snapshot can't be wrong the way an inverse operation can."
| Role | Responsibility | In a form builder |
|---|---|---|
| Originator | Creates snapshots, restores from them | FormDesign |
| Memento | Holds the state, opaque to others | Private Snapshot record behind IFormMemento |
| Caretaker | Stores and orders mementos, never reads them | UndoHistory |
| Memento | Command with Undo |
|
|---|---|---|
| Stores | Whole state (or a reference to immutable state) | Operation plus data to reverse it |
| Memory | Higher, unless immutable sharing | Low |
| Correctness risk | Low: restore is a replace | Each Undo must exactly invert Execute |
| Good for | Complex state, many small edits, multi-field changes | Discrete operations with clear inverses |
| Technique | Effect |
|---|---|
| Immutable records | Previous instance is the snapshot; no copy |
ImmutableList<T> / ImmutableDictionary<K,V> |
Structural sharing; O(log n) new nodes per change |
| Coalescing | Merge edits within, say, 500 ms into one undo entry |
| Capped history | Keep the last N snapshots |
A browser-based form designer backed by a .NET API kept a deep-copied FormDefinition per edit on the server for undo. Large forms (about 3,000 fields) used roughly 40 MB per session after an hour. Switching to immutable records with ImmutableList<T>, coalescing edits within 500 ms and capping history at 100 entries brought that to under 2 MB per session with identical undo behaviour.
Checks that the candidate can implement snapshots without breaking encapsulation, understands the memory implications and the role of immutability, and can compare Memento with Command and event sourcing.
Green flags
with is shallow.Red flags
with deep-copies.Caretaker (UndoHistory) Originator (FormDesign)
stack<IFormMemento> ──Save()──▶ Save() → new Snapshot(state)
◀──Restore()─ Restore(m) → state = ((Snapshot)m).state
«interface» IFormMemento (public, exposes nothing useful)
▲
Snapshot (private nested record inside FormDesign)
GoF describes a "wide" interface for the originator and a "narrow" one for everyone else. C# expresses that with a public marker interface and a private nested implementation.
| Approach | Who can read the state | Notes |
|---|---|---|
| Private nested record + public marker interface | Only the originator | Strongest; caretaker holds the interface |
internal members on a public memento class |
The originator's assembly | Fine if the domain lives in its own project |
| Public record of state | Everyone | Not really Memento; acceptable for simple DTO-like state |
| Serialised blob (JSON) | Anyone who deserialises it | Useful for persistence; needs versioning |
With mutable state, a snapshot must copy (and a shallow copy shares nested mutable objects, so later edits corrupt old snapshots). With immutable state, the current values can't change, so keeping a reference is a correct snapshot.
ImmutableList<T> is a balanced binary tree; Add, SetItem and RemoveAt create O(log n) new nodes and share the rest with the previous version. Reads are O(log n) rather than O(1), so for small, read-heavy lists ImmutableArray<T> (copy on write) can be better. Records give value equality and with expressions, but with is a shallow member-wise copy: a List<T> property is shared between the old and new record.
dotnet-counters.Autosaved drafts are mementos written to storage. Once persisted, they need a schema version: add a Version field and upgrade old snapshots on load, or a deployment will fail to restore last week's drafts. Keep personal data in mind: a draft history may retain information the user deleted, which matters for privacy obligations such as APP 11's requirement to destroy or de-identify information no longer needed.
Event sourcing persists the sequence of events (FieldAdded, FieldRenamed) and rebuilds state by replaying them. That gives a complete history and audit trail. Replaying thousands of events on every load is slow, so stores take a snapshot every N events: a memento of the aggregate's state at version V. Loading means: read the latest snapshot, then replay events after V. Snapshots must be versioned and are disposable: they can always be rebuilt from events.
EF Core's change tracker uses a related idea: it keeps original values for each tracked entity (a snapshot) to detect changes at SaveChanges.
FormDesign with a private nested snapshot and an UndoHistory; confirm the caretaker can't access the fields.List<T> and a shallow copy; show an old snapshot changing after an edit.ImmutableList<T> and benchmark snapshot cost for 10,000 fields with BenchmarkDotNet's [MemoryDiagnoser].Undo.An originator with opaque mementos, a capped caretaker, and immutable records as snapshots.
namespace Designer;
using System.Collections.Immutable;
public sealed record Field(string Name, string Type, bool Required);
// The narrow interface: the caretaker can hold it but learns nothing from it
public interface IFormMemento
{
DateTimeOffset TakenAt { get; }
}
// Originator
public sealed class FormDesign(TimeProvider clock)
{
private string _title = "Untitled";
private ImmutableList<Field> _fields = []; // structural sharing: snapshots don't copy the list
public string Title => _title;
public IReadOnlyList<Field> Fields => _fields;
public void Rename(string title) => _title = title;
public void AddField(Field field) => _fields = _fields.Add(field);
public void RemoveField(string name) => _fields = _fields.RemoveAll(f => f.Name == name);
public IFormMemento Save() => new Snapshot(_title, _fields, clock.GetUtcNow()); // O(1): just references
public void Restore(IFormMemento memento)
{
if (memento is not Snapshot s)
throw new ArgumentException("Memento was not created by this designer.", nameof(memento));
_title = s.Title;
_fields = s.Fields;
}
// The wide interface: only FormDesign can see inside
private sealed record Snapshot(string Title, ImmutableList<Field> Fields, DateTimeOffset TakenAt) : IFormMemento;
}
// Caretaker: orders and caps mementos, never reads them
public sealed class UndoHistory(int capacity = 100)
{
private readonly LinkedList<IFormMemento> _undo = new();
private readonly Stack<IFormMemento> _redo = new();
public void Record(IFormMemento before)
{
_undo.AddLast(before);
if (_undo.Count > capacity) _undo.RemoveFirst(); // cap memory
_redo.Clear(); // a new edit invalidates redo
}
public void Undo(FormDesign design)
{
if (_undo.Last is not { } last) return;
_redo.Push(design.Save());
_undo.RemoveLast();
design.Restore(last.Value);
}
public void Redo(FormDesign design)
{
if (!_redo.TryPop(out var next)) return;
_undo.AddLast(design.Save());
design.Restore(next);
}
}
// var design = new FormDesign(TimeProvider.System);
// var history = new UndoHistory();
// history.Record(design.Save()); design.AddField(new Field("Email", "email", true));
// history.Record(design.Save()); design.Rename("Signup");
// history.Undo(design); // title back to "Untitled", Email field still there
namespace Designer;
using System.Collections.Immutable;
// When the whole state is an immutable record, the previous instance IS the memento
public sealed record FormState(string Title, ImmutableList<Field> Fields)
{
public static FormState Empty { get; } = new("Untitled", []);
}
public sealed class RecordBasedEditor
{
private readonly Stack<FormState> _undo = new();
public FormState Current { get; private set; } = FormState.Empty;
public void Apply(Func<FormState, FormState> edit)
{
_undo.Push(Current); // snapshot = keep the old reference
Current = edit(Current);
}
public void Undo()
{
if (_undo.TryPop(out var previous)) Current = previous;
}
}
// editor.Apply(s => s with { Title = "Signup" });
// editor.Apply(s => s with { Fields = s.Fields.Add(new Field("Email", "email", true)) });
// Note: 'with' is shallow. A mutable List<T> property would be shared between states and break undo.
internal members in a domain assembly.with expression makes a deep copy. Why it is wrong: with copies members shallowly; reference-type members are shared. Instead: Make nested members immutable too.Memento is less about the pattern's classes and more about choosing a state model that makes snapshots cheap and correct. Immutable state turns Memento from "copy everything carefully" into "keep a reference", which is why I push for immutable records and collections in anything with undo, drafts or time travel.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Memento with immutable state | Undo/redo, drafts, complex multi-field edits | O(log n) per change with structural sharing | Very large state with frequent tiny edits and no sharing |
| Memento with deep copies | Small state, mutable model you can't change | Full copy per snapshot | Large graphs or per-keystroke snapshots |
| Command undo | Discrete operations with clear inverses | Each Undo must be correct |
Edits that touch many fields at once |
| Event sourcing + snapshots | You need full history and audit anyway | Infrastructure, event versioning | Just an undo button |
I measure it with BenchmarkDotNet ([MemoryDiagnoser] on save and restore) and with session memory in production; the number to watch is bytes per undo entry.
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.
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.
Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.
Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.
The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.
How to tell it (STAR)
**S:** At [company], our form designer's API instances were restarting under load because each editing session used about [40 MB]. **T:** I was asked to cut memory without changing undo behaviour users relied on. **A:** Using `dotnet-gcdump` diffs I found the undo stacks deep-cloned the whole form on every edit. I added a cap and edit coalescing as an immediate fix, then moved the state to immutable records with `ImmutableList<T>` so a snapshot became a reference, with an opaque memento type so nothing outside the designer could change snapshots. **R:** Memory per session fell to under [2 MB], restarts stopped, and large-form edit latency improved by [about 60%].
Last updated 18 Nov 2026.