Do I need to include the 'this' when using a property name in a closure?

Posted by Scott Whitlock on Stack Overflow See other posts from Stack Overflow or by Scott Whitlock
Published on 2010-05-03T02:01:16Z Indexed on 2010/05/03 2:08 UTC
Read the original article Hit count: 300

Filed under:
|

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 changed, so I want to store the undo action where I would set 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(SomeObject newChildObject)
    {
        // copies the reference
        SomeObject existingObject = myChildObject;
        m_undoActions.Add(() => myChildObject = existingObject);
        myChildObject = newChildObject;
    }
}

Looking at the lambda expression, existingObject is a local variable, so it's using a closure to pass a reference to that variable, but what about the property myChildObject? 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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about closures