0

Sorry it's a little dumb...

List<Action> ps = new List<Action>();
for (int i = 0; i < 10; i++)
{
    var k = i;
    ps.Add(() => Console.WriteLine($"print {k}"));
}
for(int i=0;i<10;i++)
{
    ps[i].Invoke();
}

// 0 1 2 ... 9

List<Action> ps = new List<Action>();
for (int i = 0; i < 10; i++)
{
    ps.Add(() => Console.WriteLine($"print {i}"));
}
for(int i=0;i<10;i++)
{
    ps[i].Invoke();
}

// 10 10 10 ... 10

Why do i have to pass a new variable k to make the delegate work?

zhaihouxi
  • 11
  • 5
  • See also: https://stackoverflow.com/questions/55938217, https://stackoverflow.com/questions/742365, https://stackoverflow.com/questions/5438307, https://stackoverflow.com/questions/37732157 – Jon Skeet Mar 06 '22 at 15:55
  • (Not "dumb" at all - frequently asked, but only because it does seem counterintuitive!) – Jon Skeet Mar 06 '22 at 15:55
  • So should I treat the delegate "captured" parameters as if they were references? Just remember to use a var k. @JonSkeet – zhaihouxi Mar 06 '22 at 16:19
  • I don't really understand what you're asking, but if you read through all those answers, you should be able to predict how any given piece of code will behave, and write code accordingly. – Jon Skeet Mar 06 '22 at 17:13
  • @Charlieface: Have never actually added more than one link to a duplicate. Doing so now... we live and learn :) – Jon Skeet Mar 06 '22 at 17:48
  • I just found there're 4 links... Thank you again! Tested the behavior using a destructor. I will carefully do some unit test from now on. – zhaihouxi Mar 06 '22 at 18:13

0 Answers0