KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've been learning C#, and I'm trying to understand lambdas. In this sample below, it prints out 10 ten times. class Program { delegate void Action(); static void Main(string[] args) { List<Action> actions = new List<Action>(); for (int i = 0; i < 10; ++i ) actions.Add(()=>Console.WriteLine(i)); foreach (Action a in actions) a(); } } Obviously, the generated class behind the lambda is storing a reference or pointer to the int i variable, and is assigning a new value to the same reference every time the loop iterates. Is there a way to force the lamda to grab a copy instead, like the C++0x syntax [&](){ ... } // Capture by reference vs. [=](){ ... } // Capture copies
Tags (comma-separated)
Save Edits
Cancel