I have created an ienumerable of lambda functions using this function
static IEnumerable<Func<int>> MakeEnumerator(int[] values)
{
for (int a = 0; a < values.Length; a++)
{
yield return () => Values[a];
}
}
I cannot then reverse this using LINQ or convert into an array without all the values becoming the last function.
Example code (note this just demonstrates the problem it is not the code in the application):
int[] start = {1,2,3};
IEnumerable<Func<int>> end = MakeEnumerator(start).Reverse<Func<int>>();
foreach (Func<int> i in end)
{
Console.WriteLine(i());
}
I think the problem is in the MakeEnumerator function. How would I modify this to make it work or go about writing a working replacement reverse function.
The problem is that you’re capturing the loop variable. All of your delegates are capturing the same variable, so they’ll always see the latest value of
a… which will bevalues.Length + 1by the time you’re executing the delegates, in your use cases. You can simply copy it instead:Alternatively (and preferrably IMO) use a
foreachloop, which currently requires the same workaround:Or better yet:
Or:
See Eric Lippert’s blog post “Closing over the loop variable considered harmful” for more information. Note that the behaviour of
foreachmay well be changing for C# 4.5.