A(nother?) question about how variable scope is applied in relation to closures. Here's a minimal example:
public class Foo { public string name; public Foo(string name) { this.name = name; } } public class Program { static Action getAction(Foo obj) { return () => Console.WriteLine(obj.name); } static void Main(string[] args) { Foo obj1 = new Foo("x1"); Action a = getAction(obj1); obj1 = new Foo("x2"); a(); } } This prints x1. It can be explained as:
getAction returns an anonymous function which has a closure enclosing the variable obj. obj has the same reference value as obj1 but its relationship with obj1 ends there as the closure encloses only obj. In other words, whatever value obj1 takes afterwards does not affect the closure. Therefore whenever/however a gets called (eg. a gets passed to some other function) it will always print x1.
Now my questions are:
- Is the above explanation correct?
- I don't have a specific scenario in mind but what if we wanted the program to print
x2(eg. closure to enclose an outer scope)? Could it be done (or doesn't it make sense to even attempt)?
objparameter asrefmight address your second question, but I'm not 100% sure of that.refparameter in closure.Foo*/ref Foofield (reference-to-a-reference, not a pointer) would be fine and understood perfectly - but that isn't a concept that can be expressed in C# (hence why I had to approximate syntax to even discuss it!), so it is perhaps reasonable that the closure has the same feature limits as hand-coding;Mainmay not refer toobjbecause the scope ofobjdoes not include methodMain. ButMaincan useFoobecause the scope of a public class does include the body ofMainin another class in the same namespace.