#1,189 – Lambda Expression Can Capture Static Data
September 24, 2014 1 Comment
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() { myStaticLambda(); } }
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.SetStaticLambda(); Dog.InvokeStaticLambda(); // Serving.. Dog.DogMotto = "We want more treats"; Dog.InvokeStaticLambda(); // Want more..