I am writing a Blazor component and noticed something unexpected. In my Razor code, I use a foreach to loop over a list, and inside the Click event handler of a RadzenButton I declare another foreach with the same loop variable name. I thought this would cause a compiler error due to a duplicate variable in scope, but the code compiles and runs fine.
@foreach(var someItem in SomeStringList)
{
<p>@someItem</p>
<RadzenButton Click="@(() => {
Console.WriteLine(someItem);
foreach(var someItem in SomeOtherStringList)
{
Console.WriteLine(someItem);
}
})">
</RadzenButton>
}
@code {
public List<string> SomeStringList = new() { "Item 1", "Item 2", "Item 3" };
public List<string> SomeOtherStringList = new() { "Item A", "Item B", "Item C" };
}
This compiles and runs fine.
But I would have expected a compiler error because I’m redeclaring the variable someItem inside the nested foreach, while outer someItem is still in scope (and even being used in the lambda for the Click handler).
My questions:
- Why does this compile without a conflict?
- How does C# handle the scope of the two
someItemvariables in this case? - Is this safe to rely on, or should I always avoid reusing variable names like this?
I tried using the same variable name someItem in both the outer and inner foreach loops. I expected the compiler to complain about a name conflict, since the outer variable is still being referenced inside the lambda expression. However, the code compiled without any error and both loops work. I want to understand why C# allows this and whether it is safe or just shadowing the variable.
<button type="button" onclick="@(() => { ...) and the behaviour is as in this questoin