delegate void writer();
static void Main(){ List writers = new List(); int i=0; for(; i < 10; i++) { writers.Add(delegate { Console.WriteLine(i); }); }
foreach (var writer in writer) { writer(); }
foreach (var writer in writer)
{
writer();
}
The answer is10101010101010101010
It will print 10 in 10 times in loop. Beacuse delegate is refrence type.
NOTE : To compile this code we need to do some correction in code as below.Replace - List writers = new List();TOList writers = new List();
and
Replace - foreach (var writer in writer)TOforeach (var writer in writers)
Exception thrown. The list is “writers”, and in loop it’s “writer”.