What will be the output of the following code that is using delegates?

    class Program
    {
        delegate void Operation();

        static void Main(string[] args)
        {
            var operations = new List<Operation>();

            for (var i = 0; i < 10; i++)
            {
                operations.Add(delegate { Console.WriteLine(i); });
            }

            foreach (var operation in operations)
            {
                operation();
            }
        }
    }
 

Experience Level: Senior
Tags: .NET C# Code challenge

Answer

Answer

  • The number 10 will be printed 10x to the output.
  • Within the for loop, the delegate captures variable i, which means the variable will be visible to the delegate method body even after the program flow gets out of the first for loop. The variable i is captured in a closure. The value of variable i is not copied. I gets accessed directly.
  • When the first for loop is left, the value of the variable i is 10.
  • The foreach loop just calls delegate method 10x and variable i that has value 10 assigned is used to write its value to the console.

Good to know

  • A delegate is a referrence type
  • It can encapsulate a named or an anonymous method
  • Whenever you declare a delegate in your program, the C# compiler generates a sealed class internally that's derived from a predefined class System.MulticastDelegate and the Multicast delegate is derived from the System.Delegate class, and both the MulticastDelegate and Delegate Classes are abstract types internally.
  • A reference to the outer variable n is said to be captured when the delegate is created. Unlike local variables, the lifetime of a captured variable extends until the delegates that reference the anonymous methods are eligible for garbage collection.
  • Closures close over variables, not over values. Every single access of captured variable in your program is accessing the same variable, there are never any copies made of it.
Related C# job interview questions