lambda and iteration variables

 
using System;

class Program
{
    public static void Main()
    {
        Action[] actions = new Action[3];

        for (int i = 0; i < 3; i++) { 
            actions[i] = () => Console.WriteLine(i);
        }
        for (int i = 0; i < 3; i++)
        {
            actions[i]();
        }
        
    }
}

The output:


3
3
3

The fix the problem:

 
using System;

class Program
{
    public static void Main()
    {
        Action[] actions = new Action[3];

        int i = 0;
        actions[0] = () => Console.Write(i);
        i = 1;
        actions[1] = () => Console.Write(i);
        i = 2;
        actions[2] = () => Console.Write(i);
        i = 3;

        for (i = 0; i < 3; i++)
        {
            actions[i]();
        }        
    }
}
  

The output:


012
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.