views:

111

answers:

6

I translated this code(it has bad side effect that it just capture the outer variable):

foreach (TaskPluginInfo tpi in Values)
{                    
    GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { tpi.ShowTask() });
}

To this code(because the above is not working):

foreach (TaskPluginInfo tpi in Values)
{                    
    // must capture the variable
    var x = tpi;
    GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { x.ShowTask(); });
}

What's the correct terminology for that work-around on that little known side effect? For now, I commented "must capture the variable." Is the word capture, the correct terminology?

A: 

closure

oykuo
+2  A: 

Well, both tpi and x are variables (of different sorts) that get captured in one of the examples... the main point here is that you want to restrict the scope of the captured variable (ideally x) to inside the loop.

So, perhaps; "capture the value of the iteration variable; not the iteration variable itself"

Marc Gravell
A: 

If TaskPluginInfo is a struct then you are capturing the value if it is a class the you are taking a reference.

James
+1  A: 

What you're actually doing is creating a closure context containing the value of the iterator for each iteration. This context will remain available to the delegate as long as the delegate exists.

How would you call the statement you're referring to? I think "capture" is a good verb to use. In the end, as long as it's clear to everyone what you mean, it's ok :-)

Philippe Leybaert
A: 

Yeah, it's capture; you can also use 'closes over'. Here are a couple of example sentences;

the delegate passed to GenerateMenu captures the variable x.

the delegate passed to GenerateMenu is a lambda that closes over x.

You might also want to google for the terms 'free variable' and 'bound variable'.

Steve Cooper
+1  A: 

Resharper's warning calls this scenario "Access to modified closure" and recommended solution is to "Capture variable" so in my comment I would say "Must capture variable to avoid access to modified closure".

zvolkov