Search code examples
c#linq

Outer Variable Trap


What exactly is the Outer Variable Trap? Explanation and examples in C# are appreciated.

EDIT: Incorporating Jon Skeet's diktat :)

Eric Lippert on the Outer Variable Trap


Solution

  • The "Outer Variable Trap" occurs when a developer expects the value of a variable to be captured by a lambda expression or anonymous delegate, when actually the variable is captured itself.

    Example:

    var actions = new List<Action>();
    for (var i = 0; i < 10; i++)
    {
        actions.Add(() => Console.Write("{0} ", i));
    }
    foreach (var action in actions)
    {
        action();
    }
    

    Possible output #1:

    0 1 2 3 4 5 6 7 8 9
    

    Possible output #2:

    10 10 10 10 10 10 10 10 10 10
    

    If you expected output #1, you've fallen into the Outer Variable Trap. You get output #2.

    Fix:

    Declare an "Inner Variable" to be captured repeatedly instead of the "Outer Variable" which is captured only once.

    var actions = new List<Action>();
    for (var i = 0; i < 10; i++)
    {
        var j = i;
        actions.Add(() => Console.Write("{0} ", j));
    }
    foreach (var action in actions)
    {
        action();
    }
    

    For more details, see also Eric Lippert's blog.