4thSpace
4thSpace

Reputation: 44312

Is this still a closure?

The testit() method is a closure. aString has fallen out of scope but testit() can still execute on it. testit2() is using a variable that hasn't fallen out of scope (mystring) but which was also not been passed into testit2(). Is testit2() considered a closure?

string mystring = "hello world";
Action testit = new Action(delegate { string aString = "in anon method"; Debug.WriteLine(aString); });
testit();

//capture mystring.  Is this still a closure?
Action testit2 = new Action(delegate { Debug.WriteLine(mystring); });
//mystring is still in scope
testit2();

In the second example, mystring can be updated outside of the method and those changes will be reflected in testit2(). This doesn't behave like a normal method, which would only be able to capture mystring as a parameter.

Upvotes: 3

Views: 415

Answers (3)

JaredPar
JaredPar

Reputation: 754763

Both examples are anonymous functions. The second of which use a closure in order to capture the local variables. The scope lifetime of the variable with respect to the anonymous function does not affect whether or not a closure is created to use it. As long as the variable is defined outside a anonymous function and used within, a closure will be created.

The first anonymous function uses no local state, therefore does not need a closure. It should compile down to a static method.

This is necessary because the anonymous function can live past the lifetime of the current function. Therefore all locals used in a anonymous function must be captured in order to execute the delegate at a later time.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500645

testit isn't as much of a closure as testit2 is really - it's only using a locally defined variable, rather than one in the "parent" environment (such as mystring).

However, I'd argue that both are closures as they have the ability to capture variables from their enclosing environment, due to anonymous methods.

Upvotes: 1

krosenvold
krosenvold

Reputation: 77171

A closure does not capture the values in scope, but the actual definition of the scope. So any other piece of code that has a reference to the same scope can modify variables within it.

Upvotes: 3

Related Questions