dotnet / roslynator

Roslynator is a set of code analysis tools for C#, powered by Roslyn.
https://josefpihrt.github.io/docs/roslynator
Other
3.04k stars 253 forks source link

Suggestion: Access to loop variable in closure #873

Open cathei opened 2 years ago

cathei commented 2 years ago

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

josefpihrt commented 2 years ago

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.

cathei commented 2 years ago

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?