0

For comment below, here's some setup code:

var allItems = new List<Item>();
allItems.Add(new Item{Id = 1});//etc etc
allItems.Add(new Item{Id = 2, ParentId = 1});//etc etc

Given the setup code; the following code:

foreach (var parentItem in parentItems)
{
    var childItems = allItems.Where(c => c.ParentId == parentItem.Id);
    ...
}

Displays a warning under parentItem.Id:

"Access to foreach variable in closure. May have different behavior when compiled with different versions of compiler."

But if I convert the above code (using ReSsharper) to the following query expression:

from parentItem in parentItems 
let childItems = allItems.Where(c => c.ParentId == parentItem.Id) 
...

I don't get the warning.

Does this syntax (seemingly equal to the foreach syntax) not have the same closure warning/problem?

Or is ReSharper not picking up this problem in the query expression syntax?

lanierhall
  • 530
  • 1
  • 5
  • 15
  • `Let is a part of a query expression. It introduces a variable` so your first example would be incorrect because it's not an expression or should I say not related to what a query expression is where you could reuse..the second one is – MethodMan Sep 11 '14 at 21:19
  • also do you understand the difference between the keyword `var` vs `let` var means the following `"It means that the type of the local variable being declared will be inferred by the compiler"` – MethodMan Sep 11 '14 at 21:26
  • Can you elaborate on your first comment, it doesn't make much sense to me. Your second comment doesn't really have anything to do with the issue. – lanierhall Sep 11 '14 at 21:28
  • I bet that would work if you were to make the `var allItems = new List();` allItems Public and not local scope it's hard to tell what one should recommend when you show partial code as well as edit what you originally had .. show the full code and what method it's in.. I think that you first example is a `scope` issue that's what I am saying – MethodMan Sep 11 '14 at 21:28
  • Also what does Item Class look like or how is it defined.. if it's a class – MethodMan Sep 11 '14 at 21:32

1 Answers1

0

In your code:

 foreach (var parentItem in parentItems)
 {
     var childItems = allItems.Where(c => c.ParentId == parentItem.Id);
     ...
 }

childItem is just a query. It hasn't actually iterated through allItems looking for parentItem.Id yet. That will happen when you say childItems.ToList(); or childItems.FirstOrDefault() or something similar.

Now, if you don't do something like that before parentItem changes, then you don't really know what it's going to be looking for.

James Curran
  • 101,701
  • 37
  • 181
  • 258