-
Notifications
You must be signed in to change notification settings - Fork 10.3k
[Blazor] Consider an analyzer to suggest using foreach instead of for in Blazor code. #16815
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Suggestion from analyzer should be "use foreach or local variable ...". |
I am strongly against it. Replacing a basic ideology with illogical one because there is a bug is an absurd. |
@YordanYanakiev this is not the bug - it is a standard C# behaviour which is simply not known to some people and sometimes it is not obvious if you are not an expert on Blazor internals. People can write loops with arbitrary complexity and it is not a trivial task to introduce some local variables (sometimes more than one) to automatically solve the problem. Here is a simple example without Blazor stuff for simplicity: for (int i = 0; i < 10; i++)
{
WriteLine(i);
if (i % 2 == 0)
i++;
WriteLine(i);
} Now let's add local variable and replace all references inside loop: for (int i = 0; i < 10; i++)
{
int x = i;
WriteLine(x);
if (x % 2 == 0)
x++;
WriteLine(x);
} I hope you see immediately that these two loops have different behaviour. |
Unfortunately I am unable to accept this misconception of the basic ideology of the procedural programming languages. This is illogical and unintuitive. Therefore it should be never part of any kind of programming language. |
We're closing this as this is a c# specific thing, rather than something specific to Blazor. |
Consider an analyzer to suggest using foreach instead of for in Blazor code, as the latter can result in undersired behaviors when the loop variable gets captured inside a lamba:
We can produce an analyzer that looks at for loops inside generated razor components and produces a warning when the loop variable is being used in an unsafe context.
I agree this is a c# behavior, but specially in the second case it happens implicitly as a result of an implementation detail, which can make it incredibly hard to troubleshoot.
The diagnostic will simply loop at the for loops and see if the loop variable is being used inside the closure.
The text was updated successfully, but these errors were encountered: