From the course: C# Hands-on Practice with Data-Structures

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Implement undo functionality with a stack

Implement undo functionality with a stack - C# Tutorial

From the course: C# Hands-on Practice with Data-Structures

Implement undo functionality with a stack

Let's implement the undo feature in this text editor application. The TextEditorService will be the main class handling this functionality. It has a currentText variable that stores the current state of the text and a method to retrieve it. The other methods are placeholders for functionality we will implement. We'll be using a stack to manage the undo actions. So let's create a stack. Now to the methods. When saving text, we'll want to push the current text onto the undo stack. This will allow us to revert to that state later on if the Undo button is pressed. Then we'll add the new text to the current text. When clearing text, we'll mostly want to do the same. We'll push the current text onto the undo stack and then set the current text equal to the empty string. To undo an item, we'll want to revert the current text back to its previous state, as long as there are items to undo. We can retrieve the previous state from the undo stack. Then we'll return true because we were able to…

Contents