Blazor component defined field inside and out side code directive
what's different between define field outside @code directive and inside it.
@{ int color = 128;}
for(int i =0; i<250 ;i++)
{
color++;
<span>@color </span>
}
<h1>@color</h1>
@code{
int color = 128;
}
i noticed that, there are difference when i use these in for.. please explain what happened and why happened.
The difference is scope and when the variable is initialized.
The stuff in your code
block is initialized before any of the markup renders, and is available to everything in the component.
The stuff in your markup is local, and exists only in the scope of the markup-- so you can put things like counters or temporary string variables there.
Think of your markup as a funny-looking C# code block, and you'll have the right idea.