Search code examples
c#lambdaforeachanonymous-methods

Terminology when copying the captured variable for a lambda/ anon-method


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?


Solution

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