Saturday, 22 January 2011

LINQ Quiz...

Can you guess the output of the following code?

var values = new List() { 100, 110, 120 };
var funcs = new List<func<int>>();
foreach (var v in values)
      funcs.Add(() => v);
foreach (var f in funcs)

If it's not "solved" I will post the answer in the next post...


  1. I will answer with a question :

    Will the following code have the same effect?
    foreach (var v in values)
    int i = v;
    funcs.Add(() => i);

  2. Perfect ;) It will not have the same output indeed!

  3. Here is why: Inside the first loop you add a new Func(Of T) in the list of funcs passing it a target value (v). That means,
    when the callback method is called the object that should be operated is the instance of v. The problem with this code is that
    v referes to an object defined in the parent method body (foreach loop) so when you actually go out of scope and invoke the delegates
    all the target values will be operated on the last instance passed as target (that is, 120). In fact if you reverse the list all the delegate targets will refer to 100.
    So, the output of the following code, for all the delegate invokations, is the last element of the List(Of T) instance, 120.
    // Output:
    // 120
    // 120
    // 120