Search code examples
c#closuresmutable

Are there any good reasons why closures aren't immutable in C#?


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.


Solution

  • 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.