roslynator icon indicating copy to clipboard operation
roslynator copied to clipboard

Suggestion: Access to loop variable in closure

Open cathei opened this issue 3 years ago • 2 comments

If you access loop variable from closure, variable value will change as loop continues. This can cause unintended behaviour and such accesses are generally discouraged. It will be helpful if Roslynator have analyzer to warn this.

ReSharper has similar feature: https://www.jetbrains.com/help/resharper/AccessToForEachVariableInClosure.html

cathei avatar Jan 12 '22 23:01 cathei

Hi,

I looked at the ReSharper page and it seems that this issue is no longer relevant:

As explained in the Eric Lippert's post, the behavior of foreach was changed in C# 5.0 (Visual Studio 2012) so that a new loop variable is generated for each iteration making it safe to use in closures.

josefpihrt avatar Mar 13 '22 10:03 josefpihrt

Whoops. I didn't know they fixed it. However the fix seems to applied only for foreach loop, not for loop. It might worth to add a warn for for loop?

cathei avatar Mar 19 '22 12:03 cathei