Master C#

How to use the Memento design pattern in C#

Take advantage of the Memento design pattern to store and restore an object's state to support undo or rollbacks in your application

How to use the Memento design pattern in C#

We use design patterns to solve common design problems and reduce the complexities in our source code. The Memento design pattern is a behavioral design pattern that can be used to provide an undo or rollback capability in an application, or simply to reset the state of an object in an ASP.Net web application, for example. By storing an object’s state to an external location called a Memento, this pattern allows that state to be restored to the object at a later time. Let’s explore how we can use the Memento design pattern in C#.

Every object has its internal state. A Memento gives us a way to save that state and restore it while still abiding by the principles of encapsulation, which dictate that non-public members of an instance of a class should not be available to the outside world. This is because the Memento is available only to the object whose state it has stored.

The participants in the Memento design pattern include a Memento, an Originator, and a Caretaker. While the Memento class stores the state of the object, the Originator creates the Memento and uses it to restore the state when needed. The Caretaker is responsible only for storing the Memento—it is not supposed to alter the Memento instance. 

Implementing the Memento pattern 

In this section we will implement the Memento design pattern in C#. We will create a simple program that has three classes – a Calculator class, a Memento class, and the client, i.e. the Main method.

To continue reading this article register now

How to choose a low-code development platform