I was discussing the little LINQ puzzle with Stephen Toub, and he brought up an idea which lead to another puzzle. I like this one even more than the previous one.

Why does the last line throw StackOverflowException?

IEnumerable<int> q = new int[] { 1, 2 };
q = from x in new int[] { 1, 2 }
    from y in q
    select x + y;

And, how come the code sample runs just fine if you switch the order of the from clauses?


5 Comments to “Another LINQ puzzle”

  1. Scorcels says:

    Do you have VB version?


  2. @Scorcels: Here is a VB version of the puzzle.

    Dim q As IEnumerable(Of Integer) = Enumerable.Range(1, 2)
    q = From x In Enumerable.Range(1, 2) _
    From y In q _
    Select x + y

  3. TJ says:

    haha, cmon people who uses VB anymore. Is it really that hard to figure out the difference between C# and VB?

  4. Roman says:

    Because there is recursive enumeration of q (-> closure) which is more evident if you rewrite it as:

    q = new int[] { 1, 2 }.SelectMany(x => q, (x, y) => x + y);

    when ToArray is called q is defined as above.

    if you switch order there is no closure
    q.SelectMany(y => new int[] { 1, 2 }, (x, y) => x + y);

  5. […] For a slightly harder challenge, check out the next puzzle. […]

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>