Loops, Lambdas, and Variables
This might be a known Razor issue, and since I haven't used Razor in ages I was caught off guard.
This does not work:
@for (int i = 0; i < items.Count; i++)
{
<CarouselItem IsActive="@(SecondIndex == i)" src="@item[i].Source" alt="@items[i].Alt">
<h5>@items[0].Header</h5>
</CarouselItem>
}
You get an exception with the h5 line (the previous lines are fine):
Uncaught Error: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.Generic.List`1[T].get_Item (System.Int32 index) <0x1f27f48 + 0x00018> in <140509c0d46c421ca83585ed625d5577>:0
at Sample.Pages.Carousels+<>c__DisplayClass0_0.<BuildRenderTree>b__10 (Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder builder3) <0x1f3d190 + 0x00090> in <14d8d1e2ea4743fa889b8a5ddf494a58>:0
The work around is to add a capture variable in the loop like so:
@for (int i = 0; i < items.Count; i++)
{
Item item = items[i];
<CarouselItem IsActive="@(SecondIndex == i)" src="@item.Source" alt="@item.Alt">
<h5>@item.Header</h5>
</CarouselItem>
}
Like I said not sure if this is fixable since it might be in Razor like that, but at the very least a better error message and adding this to the docs would be helpful.
In your first block of code you have this line
<h5>@item[0].Header</h5>
which seems to reference an array item (as opposed to items) that is apparently not anywhere else aforementioned.
try this. you would need to use local variable for it to work
@for (int i = 0; i < items.Count; i++)
{
var local_i = i;
<CarouselItem IsActive="@(SecondIndex == local_i)" src="@item[local_i].Source" alt="@items[local_i].Alt">
<h5>@item[0].Header</h5>
</CarouselItem>
}
@felyperennan That was a typo when copying and pasting into the issue. @dlr1 Thanks, but that is basically the same as my workaround :) Anyway, point being if it is something that can't be fixed because it is in Razor, I just think it should be noted in the docs, I happened to remember that issue from my C#/Razor days, but a newbie wouldnt know that.
I opened a similar one aspnet/Blazor#665
This is a general C# question about how loops and lambda hoisting interact. The answer is that foreach is different from for, in that for conceptually defines a new loop variable for each iteration, whereas for does not (it's the same variable across all iterations). Please see C# docs for more about this.