#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



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,188 – Lambda Expression Can Capture Instance Data

  1. Pingback: Dew Drop – September 23, 2014 (#1861) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: