Reputation: 23214
Assume I have the following code:
for(int i=0;i<10;i++)
{
//"i" is captured in the closure passed to LazyCreate
MyApi.AddLazyCreate(() => new foo(/*other params*/ i));
}
This will result in an unintentional behavior since "i" will be 10 for all the added closures.
Is there a safe way to avoid this?
e.g. if I design my api using an Expression<func<foo>>
if each "AddLazyCreate" examines the expression passed and store copies of those values, then it should be possible to acheive the intended behavior, right?
that is, I have to compile each argument from the expression and get the temporal value of the argument and recreate the new expression using the evaluated args.
(the expression will always be a "new" expression)
Or am I missing something fundamental here? Are thre edgecases where I will still get weird behaviors?
Upvotes: 3
Views: 206
Reputation: 1618
You can just do this:
for(int i=0; i<10; i++)
{
int number = i;
MyApi.AddLazyCreate(() => new foo(/*other params*/ number));
}
This will cause it to capture a different number on each iteration of the loop.
Upvotes: 4