ImmutableUndoRedo
A lightweight, flexible and easy to use do/undo/redo implementation based on immutable objects for .NET.
Getting started
To install ImmutableUndoRedo run the following command from the Package Manager Console:
PM> install-package ImmutableUndoRedo
Sample
Activity implementation
internal class Activity : IActivity<Activity>
{
private readonly int id;
private readonly int doCalls;
private readonly int undoCalls;
public Activity(int id)
{
this.id = id;
}
private Activity(int id, int doCalls, int undoCalls)
: this(id)
{
this.doCalls = doCalls;
this.undoCalls = undoCalls;
}
public Activity Do()
{
Console.WriteLine("Do activity #{0}", this.id);
return new Activity(this.id, this.doCalls + 1, this.undoCalls);
}
public Activity Undo()
{
Console.WriteLine("Undo activity #{0}", this.id);
return new Activity(this.id, this.doCalls, this.undoCalls + 1);
}
public override string ToString()
{
return $"Activity {{Id = {this.id}, #Do calls = {this.doCalls}, #Undo calls = {this.undoCalls}}}";
}
}
Use of the History class
class Program
{
static void Main(string[] args)
{
var history = History<Activity>.Create()
.Do(new Activity(1))
.Do(new Activity(2))
.Do(new Activity(3))
.Do(new Activity(4))
.Do(new Activity(5))
.Undo()
.Undo()
.Undo()
.Redo();
Console.WriteLine("\n\nDone activities:");
var done = new List<Activity>();
history.CopyDoneTo(done);
done.ForEach(Console.WriteLine);
Console.WriteLine("\n\nUndone activities:");
var undone = new List<Activity>();
history.CopyUndoneTo(undone);
undone.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
// Console output:
Do activity #1
Do activity #2
Do activity #3
Do activity #4
Do activity #5
Undo activity #5
Undo activity #4
Undo activity #3
Do activity #3
Done activities:
Activity {Id = 1, #Do calls = 1, #Undo calls = 0}
Activity {Id = 2, #Do calls = 1, #Undo calls = 0}
Activity {Id = 3, #Do calls = 2, #Undo calls = 1}
Undone activities:
Activity {Id = 5, #Do calls = 1, #Undo calls = 1}
Activity {Id = 4, #Do calls = 1, #Undo calls = 1}