I have the following code:
foreach (var parent in parents)
{
var children = data.Find<Order>(x=>x.ParentOrderId==parent.OrderId).ToList();
// Do stuff with the children variable
}
Resharper is telling me that I have an Access to Modified closure issue on the parent variable. But doesn’t calling ToList() mean that it will be evaluated right away?
Does that negate the need to do this?
foreach (var parent in parents)
{
var parentClosure = parent;
var children = data.Find<Order>(x=>x.ParentOrderId==parentClosure.OrderId).ToList();
// Do stuff with the children variable
}
That is exactly why “Access to modified closure” is just a warning, not an error. Basically, as long as that closure (any reference to it) cannot escape one iteration of the loop body, you are fine.
And since, as you mentioned,
.ToList()evaluates the IEnumerable holding the closure, you’re fine and this warning is, indeed, harmless and you can safely suppress it with a comment.In order for ReSharper to know when this warning is serious, not only would it have to perform escape analysis on the closure, it would also have to know how both
Find<T>and.ToList()behave with respect to keeping a hold of the closure. This will probably not happen anytime soon.