Tutorials Design Patterns in C#
Memento Pattern — Complete Guide
Memento Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 18 of 69
Memento Pattern
GoF Core ✓ → Enterprise → Cloud & Craft
Enterprise · 2 — App patterns · ~6 min · Module 3: Behavioral Design Patterns
What is this?
Memento snapshots an object’s state so you can restore it later — undo without exposing internals.
Why should you care?
ShopNest seller “product editor” needs undo after a bad edit.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public sealed class ProductEditor
{
public string Title { get; set; } = "";
public decimal Price { get; set; }
public ProductMemento Save() => new(Title, Price);
public void Restore(ProductMemento m) { Title = m.Title; Price = m.Price; }
}
public sealed record ProductMemento(string Title, decimal Price);
public sealed class EditorHistory
{
private readonly Stack<ProductMemento> _undo = new();
public void Push(ProductMemento m) => _undo.Push(m);
public ProductMemento Pop() => _undo.Pop();
}
var ed = new ProductEditor { Title = "Tee", Price = 499 };
var hist = new EditorHistory();
hist.Push(ed.Save());
ed.Title = "Tee Broken";
ed.Restore(hist.Pop());
Console.WriteLine(ed.Title);
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Save captures state; Restore applies it.
- History holds mementos.
- Keep mementos immutable snapshots.
Practice next
- Undo the bad title change.
- Push two snapshots and undo twice.
- Do not let UI mutate memento fields.
- Add redo stack.
- Include Tags in the memento.
Remember
Snapshot + restore. Opaque to outsiders. Great for undo.
ShopNest product editor undo
Seller hits Undo after a typo.
Outcome: Previous title/price restored instantly.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!