I was reading C# 4 in a Nutshell and I’ve come to this piece of code:
IQueryable<Product> SearchProducts (params string[] keywords)
{
IQueryable<Product> query = dataContext.Products;
foreach (string keyword in keywords)
{
string temp = keyword;
query = query.Where (p => p.Description.Contains (temp));
}
return query;
}
Right after the code there’s a ‘warning’ that goes like this:
The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop.
I don’t get it, I don’t understand why the temp variable is necessary. What is the outter variable trap?
From: http://www.albahari.com/nutshell/predicatebuilder.aspx
Can anybody please clarify this?
Because there is only one variable called
keywordthat is closed over. The temporary variable, however, is different each iteration.Thus, without the temporary variable, when the lambda is executed later,
keywordevaluates to the last value it was assigned in the loop.Another solution, in some cases, is to force the evaluation (and end up with a
Listor such).