1.

What can be the output of the following program?

Answer»
public class Program
{
public static void Main(string[] args)
{
var values = new List<int>() { 1, 2, 3, 4 };
var funcs = new List<Func<int>>();
foreach(var v in values)
funcs.Add( ()=>v );
foreach(var f in funcs)
Console.WriteLine(f());
}
}

The output will be:

4
4
4
4

Explanation:

The correct value of the above code will be “4 4 4 4” and not “1 2 3 4”. Let us see why.

We are creating a delegate of functions using statement 

foreach(var v in values)
funcs.Add( ()=>v );

So the loop will traverse for all values as v, i.e. 1, 2, 3, till 4. Now when ()=>v is used, it means to return the latest value of variable v, and not the value when delegate was created. Therefore when the methods run, the last value assigned to v was 4, so the methods will be called using value 4 each time, and hence the output will be 

“4
4
4
4”




Discussion

No Comment Found