I'm trying to implement undo functionality with C# delegates. Basically, I've got an UndoStack that maintains a list of delegates implementing each undo operation. When the user chooses Edit:Undo, this stack pops off the first delegate and runs it. Each operation is responsible for pushing an appropriate undo delegate unto the stack. So suppose I have a method called "SetCashOnHand." It looks like this:
public void SetCashOnHand(int x) {
int coh = this.cashOnHand;
undo u = () => this.setCashOnHand(coh);
this.cashOnHand = x;
undoStack.Push(u);
}
So this method constructs an undo delegate, does the operation, and (assuming it succeeds) pushes the undo delegate onto the UndoStack. (UndoStack is smart enough that if undoStack.Push is called in the context of an undo, the delegate goes on the redo stack instead.)
My trouble is that it's a little annoying to "cache" this.cashOnHand into the coh variable. I wish I could just write this:
undo u = () => this.setCashOnHand(this.cashOnHand);
But of course that won't get the present value of cashOnHand; it defers looking up the value until the delegate is called, so the code winds up doing nothing. Is there any way I can "dereference" cashOnHand when constructing the delegate, other than stuffing the value into a local variable like coh?
I'm not really interested in hearing about better ways to do Undo. Please think of this as a generic question about delegates, with Undo just the example to make the question more clear.