Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 412
Alex Fort Avatar asked Jan 27 '09 15:01

Alex Fort


People also ask

How are closures useful?

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.

What are C# closures?

In C#, the capability that allows a method or a function to reference a non-local variable or value is called closure.

What is closure type?

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.


2 Answers

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.

like image 122
yfeldblum Avatar answered Nov 15 '22 12:11

yfeldblum


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.

like image 39
Amy B Avatar answered Nov 15 '22 10:11

Amy B