Junior — Middle
Can you give an example when a rollback or undo of a previous action was performed in a program or system?
sobes.tech AI
Answer from AI
An example of undo action in a C# program is the use of the "Command" pattern with undo support. For example, in a text editor:
public interface ICommand
{
void Execute();
void Undo();
}
public class InsertTextCommand : ICommand
{
private StringBuilder _text;
private string _insertedText;
private int _position;
public InsertTextCommand(StringBuilder text, string insertedText, int position)
{
_text = text;
_insertedText = insertedText;
_position = position;
}
public void Execute()
{
_text.Insert(_position, _insertedText);
}
public void Undo()
{
_text.Remove(_position, _insertedText.Length);
}
}
Here, the Undo method cancels the text insertion action, restoring the state before the command was executed. This approach is often used to implement undo operations in applications and systems.