#1,189 – Lambda Expression Can Capture Static Data

A lambda expression set within a static method can make use of a class’ static data.  If the static data changes after the lambda is defined, invoking the lambda later will reflect the new (modified) static data.

Suppose that we have a Dog.SetStaticLambda method that defines a lambda using some static data:

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

        public Dog(string name)
            Name = name;

        public static string DogMotto;

        private static Action myStaticLambda;

        public static void SetStaticLambda()
            myStaticLambda = () => Console.WriteLine("Motto: {0}", DogMotto);

        public static void InvokeStaticLambda()

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

            Dog.DogMotto = "Serving mankind for generations";
            Dog.InvokeStaticLambda();  // Serving..

            Dog.DogMotto = "We want more treats";
            Dog.InvokeStaticLambda();  // Want more..


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

One Response to #1,189 – Lambda Expression Can Capture Static Data

  1. Pingback: Dew Drop – September 24, 2014 (#1862) | 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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: