Is there any elegant way to "freeze" the variables used in an action that is returned from a method?
Just have a look at the following code:
static void Main(String[] args)
{
foreach(Action a in ClosureTrap("a", "b"))
{
a();
}
}
static List<Action> ClosureTrap(params String[] strings)
{
List<Action> result = new List<Action>();
foreach(String s in strings)
{
result.Add(() => Console.WriteLine(s));
}
return result;
}
This code will write two lines to the console, both containing "b". The reason for this is not too hard to find: The last value for "s" in ClosureTrap is "b".
Is there any elegant way to get two lines "a" and "b" as output on the console?
Currently I am using an additional method to create the delegate. But by doing this, the closures loose a lot of their elegance:
static List<Action> ClosureTrap(params String[] strings)
{
List<Action> result = new List<Action>();
foreach(String s in strings)
{
result.Add(Freeze(s));
}
return result;
}
static Action Freeze(String s)
{
return () => Console.WriteLine(s);
}
Is there a better way to do this?