Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Action in Foreach

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);}));
}
like image 346
user1868675 Avatar asked Mar 31 '13 12:03

user1868675


2 Answers

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).

like image 74
Sergey Kalinichenko Avatar answered Oct 29 '22 07:10

Sergey Kalinichenko


Try using a temp variable.

foreach(Fruit f in _Fruits)
{
   var temp = f;
   field.Add(new Element(temp.ToString(),delegate{fMethod(temp);}));
}
like image 32
scartag Avatar answered Oct 29 '22 05:10

scartag