2
Reply

What is the output of the program below? Explain your answer.

delegate void writer();

static void Main()
{
List writers = new List();
int i=0;
for(; i < 10; i++)
{
writers.Add(delegate { Console.WriteLine(i); });
}

  1. foreach (var writer in writer)
  2. {
  3. writer();
  4. }

}

    The answer is
    10
    10
    10
    10
    10
    10
    10
    10
    10
    10

    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();
    TO
    List writers = new List();

    and

    Replace - foreach (var writer in writer)
    TO
    foreach (var writer in writers)

    Exception thrown. The list is “writers”, and in loop it’s “writer”.