BehavioralC#verifiedVerified

Memento Pattern in C#

Captures and externalizes an object's internal state without violating encapsulation, allowing the object to be restored to that state later.

How to Implement the Memento Pattern in C#

1Step 1: Memento stores a snapshot of the originator's state

public record Memento(string State, DateTime CreatedAt);

2Step 2: Originator creates and restores from mementos

public class TextEditor
{
    public string Content { get; set; } = "";

    public Memento Save() =>
        new(Content, DateTime.UtcNow);

    public void Restore(Memento memento) =>
        Content = memento.State;
}

3Step 3: Caretaker manages memento history

public class History
{
    private readonly Stack<Memento> _snapshots = new();

    public void Push(Memento memento) => _snapshots.Push(memento);

    public Memento? Pop() =>
        _snapshots.TryPop(out var m) ? m : null;

    public int Count => _snapshots.Count;
}

// Usage:
// var editor = new TextEditor { Content = "Hello" };
// var history = new History();
// history.Push(editor.Save());
// editor.Content = "World";
// editor.Restore(history.Pop()!);
// Console.WriteLine(editor.Content); // "Hello"

Memento Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Memento Pattern in the Real World

Think of a video game save point. When you save, the game (originator) packages your character's stats, inventory, and position into a save file (memento). The save system (caretaker) stores these files without understanding their contents. When you die and reload, the save file is handed back to the game, which restores everything exactly as it was.