tags:

views:

71

answers:

1

I'm using a list of Actions to store an undo history for an object. Let's say I have a property of my object called myChildObject and it's being mutated by a method call, so I want to store the undo action where I would mutate it back to it's current value:

public class Class1
{
    public Class1()
    {
    }

    private readonly List<Action> m_undoActions = new List<Action>();

    private SomeObject myChildObject { get; set; }

    public void ChangeState()
    {
        m_undoActions.Add(() => myChildObject.UndoChangeState());
        myChildObject.ChangeState();
    }
}

Looking at the lambda expression, is the reference to myChildObject (the object) passed or is the reference to 'this' passed. Do I need to use 'this' to preface it? Do I need to make a copy of the 'this' reference to a local variable first?

Thanks for helping me understand this closure stuff.

+3  A: 

No, there's no more need to explicitly designate a member as an instance member within a lambda than there is outside of the lambda.

Adam Robinson
Sorry, I changed my question to make it clearer. I'm trying to figure out what's passed into the closure: a reference to 'this' or a reference to the child object itself?
Scott Whitlock
What you have now is not a true closure. This will just cause an instance method to be created instead of a static method.
Adam Robinson
If I wanted to make it a true closure, would I create a local variable, like: var me = this; and then call me.myChildObject.UndoChangeState() in the lambda?
Scott Whitlock
That would create a closure, yes. But that would add (needless) complexity to the generated code over what the current example creates.
Adam Robinson
You're confusing me. Aren't closures and instance methods orthogonal? If it compiles down to an instance method, it could still use a closure if I wanted to pass another variable from ChangeState into myChildObject.ChangeState, right?
Scott Whitlock
The two are not related. A closure (as you correctly guess) means that you're involving a local variable in the anonymous function. This has the side-effect of creating a compiler generated class.
Adam Robinson