5

fMethod is an Action<Fruit>.

But when fMethod is called, the parameter is always the last entry of _Fruits.
How to solve this?

foreach(Fruit f in _Fruits)
{
   field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
ssilas777
  • 9,672
  • 4
  • 45
  • 68
user1868675
  • 127
  • 1
  • 5
  • possible duplicate of [Is there a reason for C#'s reuse of the variable in a foreach?](http://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach) – Joey Mar 31 '13 at 12:10

2 Answers2

10

This is a well-known problem of using a modified clause in a call that creates a delegate. Adding a temporary variable should solve it:

foreach(Fruit f in _Fruits)
{
    Fruit tmp = f;
    field.Add(new Element(f.ToString(),delegate{fMethod(tmp);}));
}

This problem is fixed in C# 5 (see Eric Lippert's blog).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Try using a temp variable.

foreach(Fruit f in _Fruits)
{
   var temp = f;
   field.Add(new Element(temp.ToString(),delegate{fMethod(temp);}));
}
scartag
  • 17,548
  • 3
  • 48
  • 52