Memento Pattern Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memento Pattern runs in O(1) time and O(n) space, in C# as in every other language.
- ✓A record with the with expression is the memento: immutable, with a compiler-generated copy constructor.
- ✓Model the memento as a record with init-only properties and immutable collection types, so with produces a genuinely independent snapshot rather than a shallow one.
- ✓The C# trap: The with expression is SHALLOW, so a record holding a List gives a snapshot that shares the list with the original and every later edit rewrites history in place.
- ✓A with expression allocates once and copies fields, so it is proportional to the record size and cheap for small states.
What Memento Pattern actually is
Memento Pattern in C#: what you actually reach for
C# implementation
using System.Collections.Immutable;
// Immutable members make 'with' a genuinely deep snapshot.
public sealed record EditorState(
string Text,
int Cursor,
ImmutableArray<int> Marks);
public sealed class Editor
{
private EditorState state = new("", 0, ImmutableArray<int>.Empty);
public EditorState Save() => state; // already immutable
public void Restore(EditorState m) => state = m;
public void Type(string s) =>
state = state with { Text = state.Text + s, Cursor = state.Cursor + s.Length };
}
// The shallow trap, with a MUTABLE member:
public sealed record Leaky(string Text, List<int> Marks);
var a = new Leaky("a", [1]);
var b = a with { Text = "b" };
b.Marks.Add(2); // a.Marks now has 2 as well
// BinaryFormatter was REMOVED in .NET 9, migrate, do not suppress.
// Use System.Text.Json with a source-generated context instead.Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Memento Pattern?
A record with the with expression is the memento: immutable, with a compiler-generated copy constructor. System.Text.Json is the supported serialiser for a persisted checkpoint. BinaryFormatter, which the classic implementation of this pattern used, was obsoleted in .NET 5, disabled by default in .NET 8 and REMOVED from the runtime in .NET 9, where it throws unless an out-of-support compatibility package is referenced; it is not an option in new code. ImmutableArray and the rest of System.Collections.Immutable give structural sharing for large state.
What is the most common C# mistake when implementing Memento Pattern?
The with expression is SHALLOW, so a record holding a List gives a snapshot that shares the list with the original and every later edit rewrites history in place. Because with reads as a value operation, this is the most common records-related bug. Using ImmutableList or ImmutableArray for those members makes sharing harmless and is the reason the immutable collections exist. Separately, any code still calling BinaryFormatter must be migrated rather than suppressed, since the removal in .NET 9 is a runtime failure and not a warning.
How does Memento Pattern actually perform in C#?
A with expression allocates once and copies fields, so it is proportional to the record size and cheap for small states. Immutable collections give structural sharing, so a snapshot after a single edit shares nearly all of its memory with the previous one and turns an undo history from O(history times state) into roughly O(total change), at the cost of slower individual element access than a plain array. System.Text.Json with a source-generated context avoids reflection and is several times faster than the reflection-based path. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.