I've been going over and over this in my head, and I can't seem to come up with a good reason why C# closures are mutable. It just seems like a good way to get some unintended consequences if you aren't aware of exactly what's happening.
Maybe someone who is a little more knowledgeable can shed some light on why the designers of C# would allow state to change in a closure?
Example:
var foo = "hello";
Action bar = () => Console.WriteLine(foo);
bar();
foo = "goodbye";
bar();
This will print "hello" for the first call, but the outside state changes for the second call, printing "goodbye." The closure's state was updated to reflect the changes to the local variable.
Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.
In C#, the capability that allows a method or a function to reference a non-local variable or value is called closure.
A closure expression produces a closure value with a unique, anonymous type that cannot be written out. A closure type is approximately equivalent to a struct which contains the captured variables.
C# and JavaScript, as well as O'Caml and Haskell, and many other languages, have what is known as lexical closures. This means that inner functions can access the names of local variables in the enclosing functions, not just copies of the values. In languages with immutable symbols, of course, such as O'Caml or Haskell, closing over names is identical to closing over values, so the difference between the two types of closure disappears; these languages nevertheless have lexical closures just like C# and JavaScript.
Not all closures behave the same. There are differences in semantics.
Note that the first idea presented matches C#'s behavior... your concept of closure semantics may not be the predominate concept.
As for reasons: I think the key here is ECMA, a standards group. Microsoft is just following their semantics in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With