Nilzor
Nilzor

Reputation: 18583

Is Resharper unnecessarily warning me about Access to modified closure here?

...so I have this code:

        foreach (var entry in list)
        {
            var marginOneEntry = otherList.FirstOrDefault(p => p.Margin == entry.Margin);                
            if (marginOneEntry == null) continue;
            // Do stuff with marginOneEntry
        }

and Resharper 5.1 warns me about "access to modified closure" for the use of entry in the compare-statement in the lambda expression. Isn't the FirstOrDefault-call cancelling this issue? Is my code bad or is this warning just a shortcoming in Resharper?

Note: I have read other topics on Access to modified closure here on SO, but I want an answer for this specific case, and to get clarified whether or not Resharper is overly sensitive on this subject.

Upvotes: 2

Views: 2520

Answers (2)

Snowbear
Snowbear

Reputation: 17274

Yes, this is an issue in Resharper since it doesn't distinguish methods with lazy evaluated result from methods which do not use given lambda in lazy evaluation. FirstOrDefault doesn't do lazy evaluation (forgot the term opposite to 'lazy') so it safe to use it in your example but usually there is no way to understand that from method's signature.

Upvotes: 3

Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

I think you made a mistake in the code above. Your .Where(p => entry.Margin == 1) precondition does not involve the element being enumerated. Did you mean p.Margin == 1 instead?

Also, instead of writing x.Where(y).FirstOrDefault() you can simply write x.FirstOrDefault(y).

Upvotes: 3

Related Questions