C# Action in Foreach

action, c#, delegates, foreach

Solution

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

Problem

`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);})); } ```

Original source

Related problems