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?