Lambda expressions are evaluated at compile time, so the below code will not generate a 100 different functions.
I'm not sure what you mean by this statement. If you're trying to create 100 delegates, each bound to a different value of i
, then you need to copy i
into a temporary variable inside the for
loop to ensure that the closures don't all refer to the same instance of i
. (See
dasblinkenlight's answer for details.)
But in this particular case, you can just use LINQ:
List<Action> actions = Enumerable.Range(0, 100)
.Select(i => (Action)(() => Execute(100100100 + i)))
.ToList();
Alternatively, if you prefer to use a loop and you're using .NET 4.5 or later, you can use foreach
with Enumerable.Range
:
List<Action> actions = new List<Action>();
foreach (int i in Enumerable.Range(0, 100))
actions.Add(() => Execute(100100100 + i));