C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Loop only displays up to 13, not 14

Chapter 5: Fast-tracked delegates: P157, first paragraph

Created: 9/20/2008
Last updated: 8/15/2010
Severity: Technical error

On page 157, in section 5.5.5, I claim that if we'd captured the index variable instead of counter, the output would have been the numbers 5 to 14. This isn't the case - it would actually be 5 to 13. Here's the code, ready to run in Snippy:

List<ThreadStart> list = new List<ThreadStart>();

for (int index=0; index < 5; index++)
{
   // counter variable is now obsolete
   int counter = index*10;
   list.Add (delegate
      {
         // index variable is captured
         Console.WriteLine(index);
         index++;
      }
   );
}

foreach (ThreadStart t in list)
{
   t();
}

list[0]();
list[0]();
list[0]();
list[1]();

And here's the output...

5
6
7
8
9
10
11
12
13

Thanks to Dave Jordan for pointing this out.