Search code examples
c#blazorblazor-server-sidenullreferenceexception

Nullable parameter in Blazor component gives "Possible null reference assignment" warning


I am using .NET 7 and I have these two Blazor components:

Child.razor:

@using System.Xml.Linq

<h3>Child</h3>

@code {
    [Parameter]
    public Func<XElement, Task<bool>>? OnDraft { get; set; }
}

Parent.razor:

@using System.Xml.Linq

<h3>Parent</h3>

<Child OnDraft="@OnDraft" />

@code {
    public Func<XElement, Task<bool>>? OnDraft { get; set; }
}

However, in Visual Studio I get a warning on line 5 in Parent.razor saying Possible null reference assignment:

enter image description here

Why does this happen when the parameter and argument both have the same nullable type?


Solution

  • A workaround seems to be to change:

    <Child OnDraft="@OnDraft" />
    

    to:

    <Child OnDraft="@(OnDraft!)" />
    

    Now there is no more warning:

    enter image description here