dotnet / razor

Compiler and tooling experience for Razor ASP.NET Core apps in Visual Studio, Visual Studio for Mac, and VS Code.
https://asp.net
MIT License
502 stars 192 forks source link

`@null` attribute value results in ambiguity #10615

Open jjonescz opened 3 months ago

jjonescz commented 3 months ago

In a .razor component:

<div style="@null">x</div> <!-- error -->
<div style="@((string?)null)">x</div> <!-- ok -->

error CS0121: The call is ambiguous between the following methods or properties: 'RenderTreeBuilder.AddAttribute(int, string, string?)' and 'RenderTreeBuilder.AddAttribute(int, string, MulticastDelegate?)'

Note that passing null to an attribute is a supported scenario: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-7.0#conditional-attribute-rendering. Although perhaps it doesn't make much sense to pass a literal @null but rather via some variable.

It also works fine in .cshtml.

Related:

I think compiler cannot do much here, we don't analyze the user-written C# code. At most we could offer an analyzer to fix this by casting.

chsienki commented 3 months ago

@jjonescz Does this still occur when using AddComponentParameter instead of AddAttribute?

jjonescz commented 3 months ago

@chsienki It's not possible to use AddComponentParameter, that's only for components, this is about normal HTML elements.

chsienki commented 3 months ago

@jjonescz Gotcha, thanks for the clarification.