开发者

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

开发者 https://www.devze.com 2023-04-11 22:23 出处:网络
...so I have this code: foreach (var entry in list) { var marginOneEntry = otherList.FirstOrDefault(p => p.Margin == entry.Margin);

...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.


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号