tags:

views:

122

answers:

1

Hi all

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  A: 

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.

dtb