Brahma Prakash Shukla
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. }

}

By Brahma Prakash Shukla in C# on Oct 17 2022
  • Naimish Makwana
    Jan, 2023 12

    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)

    • 0
  • Deen Core
    Dec, 2022 13

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

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS