I created a list of delegates and add following anonymous delegate for each value of variable i
:
delegate {Console.WriteLine(i); }
I was expecting it to print 3 ten times because while invoking each delegate, I am passing 3 as the argument. But, it is printing 10 ten times.
Following is the code:
using System;
using System.Collections.Generic;
namespace ConsoleApplication
{
public class Program
{
static void Main(string[] args)
{
ShowUsingDelegates();
Console.ReadLine();
}
delegate void MyDelegate(int i);
static void ShowUsingDelegates()
{
var myDelegates = new List<MyDelegate>();
for (int i = 0; i < 10; i++)
{
myDelegates.Add(delegate {Console.WriteLine(i); });
}
foreach (var a in myDelegates)
{
a.Invoke(3);
}
}
}
}