I have a quick question hopefully about Action
types and Lambdas in C#. Here's come code:
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
for (int I = 0; I < 10; I++)
actions.Add(new Action(() => Print(I.ToString())));
foreach (Action a in actions)
{
a.Invoke();
}
actions.Clear();
int X;
for (X = 0; X < 10; X++)
{
int V = X;
actions.Add(new Action(() => Print(V.ToString())));
}
foreach (Action a in actions)
{
a.Invoke();
}
Console.ReadLine();
}
public static void Print(string s)
{
Console.WriteLine(s);
}
If you run this code you will see that it outputs 10, ten times in a row, then outputs the numbers 0-9 the second time around. It clearly has something to do with the way I use X vs I, and how I give my action a new variable V each time in the second loop... Possibly that each new V is a new address in memory, but I'm struggling to understand why I.ToString() doesn't do the same thing in the first loop... Why doesn't I.ToString() used in the first Action work in the same way as the second example?