I just came across the most unexpected behavior. I\'m sure there is a good reason it works this way. Can someone help explain this?
Consider this code:
Since the foreach construct is just syntactic sugar it is best to think of it in it's true form.
foreach
int num; while (nums.MoveNext()) { num = nums.Current; actions.Add(() => num); }
The lambda will capture the num variable so when you execute the lambda the latest value of num will be used.
num