Magnus Mårtensson
Microsoft Regional Director, Azure MVP, CEO Loftysoft
Avirag Jain
Director & CTO R Systems
Mahesh Chand
Founder C# Corner, CEO Mindcracker
Chris Gali
CEO & Co-Founder Graphite
Subinder Khurana
Chief Architect StoryProcess, Founder NASSCOM DeepTech Club
Bryan Rishforth
Investor, Chairman Graphite
Bryn Everson
Director Biz Dev Graphite
Raj Tiwari
Digital Transformation Leader, Futurist and Visionary
Joseph Guadagno
Microsoft MVP, Lead Quicken Loans
Nikita Sachdev
Entrepreneur, Blockchain Enthusiast & Advisor, Social Media Influencer
Doug Wagner
COO & Founder Adapt Technical Group
Ritesh Modi
Architect, Senior Evangelist, Cloud Architect
Crystal Wenrick
Director Communications Mindcracker
Allen O’Neill
Microsoft MVP, Consulting Engineer/Architect
Praveen Kumar
CEO MCN Solutions
Chris Love
Founder Love2Dev, Microsoft MVP, Author
Sanjay Vyas
Microsoft Regional Director, Microsoft MVP, Founder & CEO SkillLabs Technologies
Veena Sarda
Deep Learning Consultant, Author
Sekhar Srinivasan
C# Corner MVP, Microsoft Certified Trainer, Pluralsight Author
Lalit Bansal
Founder & CEO - EIY SYS
Navdeep Garg
CEO Revinfotech
Prakash Tripathi
Tech Manager/Leader, Microsoft MVP, Blogger
Bhavna Jain
Breakthrough Consultant
Naveen Sharma
Enterprise Architect, Leadership Coach, Author
Vidya Vrat Agarwal
Principal Architect, Microsoft MVP, Author
Sheetal Agarwal
Founder Clownselors, Medical Clown, Trainer
Abhishek Kant
Founder GTM Catalyst
Vishnu Saran
Founder & CEO VoiceQube
Sandeep Soni
Founder & CEO Deccansoft, Microsoft Certified Trainer
Parveen Malik
AVP InfoSec & Vulnerability Management, Information Security Expert
Nitin Pandit
Microsoft MVP, Developer Evangelist, Author
Niloshima Srivastava
C# Corner MVP, Tech Architect, Trainer, Blogger
Bala Chirtsabesan
Senior Software Engineer at Microsoft, Author
Manoj Mittal
Sr. Technical Architect, C# Corner MVP, Author
Chandni Di
Co-Founder Voice of Slum
Vithal Wadje
Technical Lead, Microsoft MVP, Author
Shivam Ahuja
Founder SkillCircle, Business Mentor
Chervine Bhiwoo
Solution Architect, Microsoft MVP, Author
Saurabh Jain
Vice President Paytm, Founder Fun2Do Labs, Author
Vinay Solanki
Head IoT at Lenovo, Founder IoT-NCR
Anshu kumari
Founder Blockchainkids, Inventor, Trainer
Amit Singal
CEO Startup Buddy
Dev Pratap
Co-Founder & CEO Voice of Slum
Amey Vartak
Technology Consultant, Full Stack Developer, C# Corner MVP, Author
Viswanatha Swamy
Principal Software Engineer, C# Corner MVP, Author
Sanket Verma
Research Engineer @ Ballistics (Forensics) and Chair, PyData Delhi
Sourabh Somani
Lead Developer, Microsoft MVP, Author
Abhishek Mishra
Software Architect, C# Corner MVP, Author
Siddharth Vaghasia
Technical Consultant, C# Corner MVP, Blogger
Bassam Alugili
Senior Software Specialist, Database Expert
S Ravi Kumar
Solution Architect, C# Corner MVP, Author
Sundaram Subramanian
Full Stack Developer, C# Corner MVP, Speaker
Deepesh Somani
Solution Architect, Microsoft MVP, Author
Debasis Saha
Technical Project Manager, C# Corner MVP, Blogger, Author
Vipul Jain
Software Architect, C# Corner MVP, Author
Akshay Patel
Technical Architect, Microsoft Certified Trainer, C# Corner MVP, Author
Stephen Simon
RPA Developer, Evangelist, Author
Vivek Sharma
Founder Kingster636, AR/VR Specialist
Jeetendra Gund
Technical Lead, C# Corner MVP, Author
Sujal Beniwal
AI Enthusiast, Student
M Viknaraj
Microsoft MVP, Azure Architect, Author
Prasham Sabadra
Software Architect, C# Corner MVP, Trainer, Author
Aakash Maurya
Senior Developer, C# Corner MVP, Speaker
Ankit Sharma
Senior Software Engineer, C# Corner MVP, Author
Mangesh Gaherwar
Team Lead, C# Corner MVP, Author
Viral Jain
Technical Consultant, C# Corner MVP, Author
Bhasker Das
Solution Architect, Evangelist
Manish Dwivedi
Associate Project Manager
Ck Nitin
Programmer, Author
Rohit Gupta
Technical Trainer, Author
Manish Tewatia
Full-stack Marketer, UX Designer
Bhavya Gaur
Technical Illustrator
Rohit Tomar
SEO/SMO Expert
Web Track
Cloud & Data Track
Dev Track
Registration & Breakfast
Future of Desktop Apps with JS (ElectronJs)
Nitin Pandit
Building Serverless Microservices Using Microsoft Azure
Vithal Wadje
Innovating RPA: A Robot for Every Person
Stephen Simon
Managing Cloud Storage Accounts using Logic Apps
Viknaraj Manogararajah
Data visualization using Python
Sekhar Srinivasan
Going Cross platform with AR Foundation
Vivek Sharma
Keynote
Managing your Azure dependencies in ASP.NET Core apps using VS
Bala Chirtsabesan
Securing Applications on Intelligent Azure
Abhishek Mishra
Getting started with Blazor the Framework of Future
S Ravi Kumar
Lunch
Build Progressive Web Apps using Angular 9
Debasis Saha
Build and deploy to any platform using Azure DevOps
Chervine Bhiwoo
Deep Dive in Azure Service Bus
Akshay Patel
Build a Native Mobile Application using React Native and JavaScript
Joseph Guadagno
Making sense of Web Job, Web Job SDK and Functions in Azure
Prakash Tripathi
CloudFront Distribution in AWS
Viral Jain
Tea Break
Introduction to PowerBI
Aakash Maurya
Build Advanced SPFx solutions with React and Graph API
Siddharth Vaghasia
Build Business Intelligence Analyst (BIA) Skills
Sundaram Subramanian
Deep dive of Power Platform – AI BUILDER
Prasham Sabadra
Panel 1
What's new in SharePoint development
Vipul Jain
Build a SSO (Single Sign On) based Native JavaScript application with Microsoft Identity within 10 minutes
Manoj Mittal
Panel 2
Applications and working of AI
Veena Sarda
Deploying serverless API's with .Net core 3.0 on AWS & Azure
Amey Vartak
Panel 3
Blockchain with .NET Core (Ark)
Anshu Kumari
Closing Note & Prize Distribution
Dev Track
Cloud Track
Architecture Track
Emerging Tech Track
Registration & Breakfast
Creating Full-Stack Web Apps Using Server-Side Blazor
Ankit Sharma
Real time face recognition with MS Cognitive Services
Niloshima Srivastava
Building Scalable APIs with GraphQL
Jeetendra Gund
Future of development with AI and Blockchain
Navdeep Garg
Debugging Tips and Tricks with Visual Studio 2019
Joseph Guadagno
Azure Containers
Abhishek Kant
Enterprise Architecture
Naveen Sharma
Bot Framework - learn it fast and look like a boss!
Allen O’Neill
Keynote
.Net Core & C# 8 Performance
David McCarter
Working with Azure kubernetes services
Ritesh Modi
Becoming an Architect
Vidyavrat Agarwal
Why Techies Need to Learn Product Management
Saurabh Jain
Lunch
Build a rules engine in .Net Core
Sanjay Vyas
Building CI and CD Pipeline using Azure DevOps
Sandeep Soni
Entity Framework Core - Tips and Tricks, Performance Optimization, and Tuning
Bassam Alugili
Hacking your way into Data Science
Sanket Verma
Speed up your .Net Core Website
Sourabh Somani
Azure
Magnus Mårtensson
Demystifying Open Distro for Elasticsearch
Suman Debnath
Future of Data
Shivam Ahuja
Tea Break
gRPC with C# and .Net Core
Mangesh Gaherwar
Panel 1
Essentials of Cloud security
Parveen Malik
Power platform and Dynamics 365
Deepesh Somani
Microservices - the gRPC Way
Viswanatha Swamy
Panel 2
Reserved
Reserved
Closing Note & Prize Distribution
Restoring state with the Memento pattern in C#
The Memento pattern sits among the original catalogue of behavioural design patterns documented in the famous Gang of Four book, and it remains one of the most elegant ways to add undo functionality to a .NET application. By saving and restoring the internal state of an object without exposing its structure, the pattern keeps encapsulation intact while still allowing travel through the object's history. For developers in Australia building line-of-business tools, from insurance claim processors in Sydney to scheduling software in Perth, this pattern offers a clean path to a familiar user expectation: the humble Ctrl+Z.
This article walks through a practical C# implementation of the pattern, examining the originator, the memento, and the caretaker in real code. Along the way, we will look at how Australian regulations around data privacy shape the way snapshots are stored, what happens when an undo needs to cross a process boundary, and how the pattern compares to related approaches such as the Command pattern.
You will find a comparison table weighing different state-restore techniques, two short lists of practical tips, and seven sections that progressively build a working solution that can be dropped into a typical WinForms, WPF, or ASP.NET Core project used by a small business anywhere from Adelaide to the Gold Coast.
Capturing the originator's state
At the heart of the Memento pattern is the originator, the object whose state needs to be saved and restored. The originator knows its internal structure intimately, and it is the only class allowed to create and read the snapshot it produces. This keeps the rest of the system from forming tight couplings to private fields, which is particularly useful when the originator holds data that might be regulated under the Australian Privacy Act 1988 or the Notifiable Data Breaches scheme.
public class Document
{
public string Title { get; private set; }
public string Content { get; private set; }
public int CaretPosition { get; private set; }
public void Type(string text)
{
Content += text;
CaretPosition = Content.Length;
}
public DocumentMemento Save() => new(Title, Content, CaretPosition);
public void Restore(DocumentMemento memento)
{
Title = memento.Title;
Content = memento.Content;
CaretPosition = memento.CaretPosition;
}
}
The Save method produces an immutable snapshot, while Restore accepts one and copies its values back. Because the memento is value-typed in spirit, the originator can be confident that no external code has tampered with it between save and restore. In a real application, an editor used by a legal team in Brisbane might add fields such as AuthorId or LastReviewer, but the principle remains the same.
Defining the memento itself
The memento is a passive data holder. It exposes no behaviour beyond letting the originator read its contents and letting the caretaker store and retrieve it. In C#, a record type is a natural fit because it gives us value-based equality, immutability by default, and a compact syntax.
public record DocumentMemento(
string Title,
string Content,
int CaretPosition);
Notice that the memento's properties are read-only. Once a snapshot is taken, it cannot be mutated, which prevents the kind of subtle bugs that appear when history entries start referring to the same object instance. This aligns well with audit expectations under frameworks such as APRA's CPS 234 for organisations operating in Australia's financial sector.
If the snapshot needs to be persisted to disk, perhaps for an editor running in a Canberra government department, the memento can be serialised to JSON or to a binary MemoryStream. Care should be taken to exclude sensitive fields from the serialised form when the snapshot crosses a trust boundary, a habit that aligns with the Office of the Australian Information Commissioner's guidance on de-identification.
The caretaker's stack of snapshots
The caretaker is responsible for keeping the history. It asks the originator for a memento at strategic moments, stores the memento in a collection, and later hands a previous memento back to the originator when the user requests an undo. A stack is the classic data structure because it gives last-in-first-out behaviour, matching how most editors handle their undo queue.
public class History
{
private readonly Stack<DocumentMemento> _undo = new();
private readonly Stack<DocumentMemento> _redo = new();
public void Snapshot(Document doc)
{
_undo.Push(doc.Save());
_redo.Clear();
}
public bool CanUndo => _undo.Count > 1;
public bool CanRedo => _redo.Count > 0;
public void Undo(Document doc)
{
if (!CanUndo) return;
_redo.Push(_undo.Pop());
doc.Restore(_undo.Peek());
}
public void Redo(Document doc)
{
if (!CanRedo) return;
doc.Restore(_redo.Pop());
_undo.Push(doc.Save());
}
}
Notice the small detail that CanUndo checks for Count > 1. We always keep one baseline state at the bottom of the stack so that the very first undo does not throw. This is a common bug in beginner implementations and worth flagging in code reviews at any .NET user group, whether that group meets in Melbourne's RMIT or Perth's Central TAFE.
Adding the pattern to a real editor
Let us put the pieces together inside a console application that simulates a text editor. The application keeps a Document and a History, and it accepts simple commands such as type, undo, and redo from the user.
var doc = new Document { Title = "Notes" };
var history = new History();
history.Snapshot(doc);
while (true)
{
Console.Write("> ");
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) break;
if (input.StartsWith("type "))
{
doc.Type(input[5..]);
history.Snapshot(doc);
}
else if (input == "undo")
{
history.Undo(doc);
}
else if (input == "redo")
{
history.Redo(doc);
}
else if (input == "show")
{
Console.WriteLine($"\"{doc.Content}\"");
}
}
Running this in a developer's terminal in Adelaide produces output similar to:
> type G'day
"G'day"
> type mate
"G'day mate"
> undo
"G'day"
> redo
"G'day mate"
> show
"G'day mate"
The Australian greeting slips naturally into the example because the data is just a string, but the same technique works for richer objects, from invoice headers to medical appointment fields in a clinic management system.
Weighing the Memento against other patterns
Developers often ask whether the Memento pattern is worth the effort when the Command pattern already exists. Both can implement undo, but they do it differently. The table below summarises the trade-offs.
| Criterion | Memento pattern | Command pattern | Direct field copy |
|---|---|---|---|
| Encapsulation | High, originator owns snapshot | Medium, command knows receiver's API | Low, full object exposed |
| Memory use | Grows with each snapshot | Grows with each action | Depends on copy depth |
| Best for | Editor state, form data, wizard steps | Transactional actions, queued jobs | Simple single-field undo |
| Complexity to implement | Low | Medium to high | Very low |
| Risk of leaking sensitive data | Medium if snapshot is serialised | Low, only inputs stored | High without deep cloning |
The pattern you choose depends on the shape of your application. A Canberra-based HR system that needs to undo complex wizard inputs benefits from Memento, while a Sydney fintech processing payment intents benefits more from Command because each action is already a discrete transaction recorded for the ATO.
Persistence, storage, and Australian data considerations
When snapshots outlive the process that created them, they have to be stored somewhere. Common choices include a SQL Server database, an SQLite file used by desktop apps, or an Azure Blob Container in the australiaeast region for cloud-hosted applications. Each choice comes with its own compliance considerations.
The Privacy Act 1988 and the Australian Privacy Principles require that personal information held by an organisation with an annual turnover above AUD 3 million be handled with care. A snapshot of an editor state may contain names, addresses, or other identifiers, so any persistence layer should encrypt the data, apply retention rules, and log access for the Notifiable Data Breaches scheme. A small bookkeeping business in Hobart running a desktop invoicing tool, for example, might store its snapshot history in a local SQLite file protected with DPAPI and never leave the workstation. A national retailer headquartered in Brisbane, on the other hand, would centralise snapshots in Azure and rely on role-based access control.
Practical storage habits for production deployments:
- Encrypt snapshots at rest using a managed key in Azure Key Vault or AWS KMS Sydney.
- Apply a retention policy that purges snapshots older than the business need.
- Log access to snapshot stores so incidents can be reported within the thirty-day window required under the Notifiable Data Breaches scheme.
- Avoid sending snapshots across international borders unless the destination country has comparable privacy laws, an issue that comes up frequently when developers choose overseas SaaS providers.
Common pitfalls and practical tips
Working with the Memento pattern for a while surfaces a handful of recurring issues. The lists below capture the ones that come up most often in Australian .NET teams.
Pitfalls to watch for in production code:
- Holding references to mutable objects inside the memento; use
recordtypes or deep clones. - Forgetting to clear the redo stack when a new action follows an undo, which silently breaks the user expectation.
- Serialising private fields without thinking about whether they contain personal information covered by the Privacy Act.
- Letting the history stack grow without bound, which can exhaust memory in long-running editors.
Habits that keep the implementation tidy:
- Keep the memento class nested inside the originator if the snapshot is never shared with other types.
- Push a baseline snapshot into the history at construction time so the first undo never throws.
- Expose
CanUndoandCanRedoproperties so the UI can disable them, the same pattern used in WPF'sCommandManager. - Consider compressing large snapshots with
GZipStreamwhen they are sent to remote storage in bandwidth-constrained regions such as far north Queensland.
By treating the memento as a first-class value object and the history as a small, focused service, you can add rich undo functionality to almost any C# application without compromising the encapsulation that makes your domain model pleasant to maintain.
1, CBD, Maharaj Surajmal Road, Near Yamuna Sports Complex, Delhi, 110032
GENERAL QUERIES
Manish Tewatia
manish@csharpcon.com
+91-9718-431-042
TICKET QUERIES
Atul Gupta
conference@csharpcon.com
+91-9910-125-804