title: C# Lambdas: How *Not* to Defer "Dereference"?
body: <p>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:</p>
  
  <pre><code>public void SetCashOnHand(int x) {
      int coh = this.cashOnHand;
      undo u = () =&gt; this.setCashOnHand(coh);
      this.cashOnHand = x;
      undoStack.Push(u);
  }
  </code></pre>
  
  <p>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.)</p>
  
  <p>My trouble is that it's a little annoying to "cache" this.cashOnHand into the coh variable. I wish I could just write this:</p>
  
  <pre><code>undo u = () =&gt; this.setCashOnHand(this.cashOnHand);
  </code></pre>
  
  <p>But of course that won't get the <em>present</em> 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?</p>
  
  <p>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.</p>