-4

hi i have a code that i dont understand what should be his ouput.

here is the code:

delegate void Employee();
static void Main()
{
                IList employees= new List<Employee>();

                for(int i=0;i<3;i++)
                {
                    employee.Add( () => Console.Write(i));
                }
                foreach(var employee in employees)
                {
                    employee();
                }
}

can anyone help me with this? what is the output and how did you found it?

Nir di
  • 53
  • 1
  • 6
  • Uhm ... paste the code in Visual Studio and execute it? – Ian H. Feb 13 '17 at 12:28
  • `Console.Write()` will output to the console. Maybe this helps: [Seeing the console's output in Visual Studio 2010?](http://stackoverflow.com/questions/5301232/seeing-the-consoles-output-in-visual-studio-2010) – Georg Patscheider Feb 13 '17 at 12:30
  • 1
    You will print `333`, but you need to declare it as `IList` instead of `IList`. – Tim Schmelter Feb 13 '17 at 12:31
  • @vc74: they are invoked in the `foreach` but they will use the last value of `i` – Tim Schmelter Feb 13 '17 at 12:33
  • That code won't compile. in the first for loop, it should be `employees.Add` not `employee.Add` – Pikoh Feb 13 '17 at 12:35
  • @Tim is right. It prints **333**. When delegates are called **i** has value **3** (first for loop end with this value) so calling delegate produce the same results. – Klaudiusz bryjamus Feb 13 '17 at 12:36
  • 1
    If you don't want this behaviour but the actual value of `i` you should not "access this modified closure"(resharper warning) but use a local variable in the loop which you assign the value of `i` – Tim Schmelter Feb 13 '17 at 12:38

1 Answers1

0

Your code as is does not compile

I think this is what you mean:

delegate void Employee(); // Note that this is equivalent to the Action delegate

static void Main(string[] args)
{
    IList employees = new List<Employee>();

    for (int i = 0; i < 3; i++)
    {
        employees.Add(new Employee(() => Console.Write(i)));
    }

    foreach (Employee employee in employees)
    {
        employee();
    }
}

which as Tim pointed out prints 333 since the i variable is captured by your 3 delegates.

Employee is not an ideal name for a delegate, at first I thought you had a class named Employee and another collection called employee but it seems the only thing you need is a collection of delegate instances.

vc 74
  • 37,131
  • 7
  • 73
  • 89