4
Answers

Using integral types when creating delegates inside a loop

Is there a good reason why I get the following output for the following code-example, or is it do to optimization of the Visual Studio 2005 compiler?

Output:
5 0 0 4
5 1 1 4
5 2 2 4
5 3 3 4
5 4 4 4

Columns 2 and 3 is what I expected.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Test
{
public delegate void TestDelegate();
   public class TestObj
   {
      private int i;
      public TestObj(int i) { this.i = i; }
      public override string ToString() { return i.ToString(); }
   }

   class Program
   {
      
public static event TestDelegate act;

      static void Main(string[] args)
      {
         
int k;
         
for (int i = 0; i < 5; i++)
         {
            int j = i;
            k = i;
            TestObj t = new TestObj(i);
            act +=
delegate() { Console.WriteLine(i + " " + t + " " + j + " " + k); };
         }
         act();
         Console.ReadLine();
      }
   }
}

Thanks!

Answers (4)
Next Recommended Forum