#1,188 – Lambda Expression Can Capture Instance Data

A lambda expression set within an instance method can make use of instance data within the object.  If the instance data changes after the lambda is defined, invoking the lambda later will reflect the new (modified) instance data.

Suppose that we have a Dog.SetLambda method that defines a lambda using some instance data:

    public class Dog
        public string Name { get; set; }

        public Dog(string name)
            Name = name;

        private Action myLambda;

        public void SetLambda()
            myLambda = () => Console.WriteLine("Dog is {0}", Name);

        public void InvokeLambda()

Below, we make use of these methods. Note that if we invoke the lambda after changing the instance data, the new data is used.

            Dog d = new Dog("Bowser");
            d.InvokeLambda();  // Bowser

            d.Name = "Lassie";
            d.InvokeLambda();  // Lassie