2

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?

1 Answer 1

2

Yes, it it safe to do. Your LINQ query expands essentially to this:

private AnonType AnonMethod(Product product)
{
    return new
        {
            ID = product.ID,
            Name = product.Name,
            Content = new Func<object,string>(
                (obj) => (GetSomeDynamicContent(obj, product))
                )
        };
}

var products = allProducts.Select(AnonMethod);
someCustomWebControl.DataSource = products;
someCustomWebControl.DataBind();

As you can see, the lambda expression captures the product variable for each product in allProducts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.