Iteration variable is used in a labda expression

2 posts, 0 answers
  1. Stuart Hemming
    Stuart Hemming avatar
    1622 posts
    Member since:
    Jul 2004

    Posted 12 Nov 2012 Link to this post

    Why is this considered something that should be considered worth warning people about?

    I ask, purely in the spirit of furthering my own eduction.

  2. Zdravko
    Zdravko avatar
    657 posts

    Posted 13 Nov 2012 Link to this post


     Thanks for contacting us.

    For an example I will give you the following code:

    var values = new List<int>() { 100, 110, 120 };
    var funcs = new List<Func<int>>();
    foreach(var v in values) 
      funcs.Add( ()=>v );
    foreach(var f in funcs) 

    In versions older than C# 5 this code will return values 120/ 120/ 120.
    Because ()=>v means "return the current value of variable v", not "return the value v was back when the delegate was created". Closures close over variables, not over values. And when the methods run, clearly the last value that was assigned to v was 120, so it still has that value.
    This is how the loop body is implemented in the versions before C# 5:
        IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator();
          int m; // OUTSIDE THE ACTUAL LOOP
            m = (int)(int)e.Current;

    and in version C# 5 the variable is moved inside the loop body so a fresh variable is created:
            int m; // INSIDE
            m = (int)(int)e.Current;

    Each closure is closed over a different variable, which is only assigned to once, so it always keeps the correct value.

    I hope I was detailed enough.

    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  3. DevCraft R3 2016 release webinar banner
Back to Top