Do I need to include the 'this' when using a property name in a closure?
- by Scott Whitlock
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.