Anonymous functions local variable hoisting is getting in the way
c#
Solution
You should change it like this:
static IEnumerable<Func<int>> GetFuncs()
{
List<Func<int>> list = new List<Func<int>>();
foreach (var i in Enumerable.Range(1, 20))
{
int i_local = i;
list.Add(() => i_local);
}
return list;
}
EDIT
Thanks to Jon Skeet, read his answer.
Problem
I know that with anonymous functions, local stack variables are promoted to a class, are now on the heap etc. So the following does not work: ``` using System; using System.Collections.Generic; using System.Linq; namespace AnonymousFuncTest { class Program { static void Main(string[] args) { foreach (var f in GetFuncs()) { Console.WriteLine(f()); } Console.ReadLine(); } static IEnumerable<Func<int>> GetFuncs() { List<Func<int>> list = new List<Func<int>>(); foreach(var i in Enumerable.Range(1, 20)) { list.Add(delegate() { return i; }); } return list; } } } ``` I know changing GetFuncs to this would work: ``` static IEnumerable<Func<int>> GetFuncs() { foreach(var i in Enumerable.Range(1, 20)) { yield return () => i; } } ``` But say I'm doing something like the following: ``` foreach (var arg in someArgList) { var item = new ToolStripMenuItem(arg.ToString()); ritem.Click += delegate(object sender, EventArgs e) { new Form(arg).Show(); }; mainMenu.DropDownItems.Add(ritem); } ``` This of course does not have the intended effect. I know why it doesn't work, just need suggestions on how to fix it so it does.