I know that lambda expressions within loops can cause problems if they use local variables. ( see http://www.jaylee.org/post/2008/11/18/Lambda-Expression-and-ForEach-loops.aspx )
Now I have a situation, where I am using a lambda expression within a LINQ query:
var products = from product in allProducts
select new
{
ID = product.ID,
Name = product.Name,
Content = new Func<object,string>(
(obj) => (GetSomeDynamicContent(obj, product))
)
};
someCustomWebControl.DataSource = products;
someCustomWebControl.DataBind();
Is this safe to do? Will the compiler always properly expand this expression and ensure that “product” points to the correct object?
Yes, it it safe to do. Your LINQ query expands essentially to this:
As you can see, the lambda expression captures the
productvariable for each product in allProducts.