.net-coreblazor

Blazor best practice for Non-nullable warnings


With blazor I get Non-nullable warnings all around the code. Those warnings seems to be wrong, however solving them introduces a lot of code with the only purpose to hide the warning while the value will never be null.

What is the best practice to solve or hide those warnings?

Example:

[Inject] private IStringLocalizer<Element> L { get; set; }
Element.razor.cs(5, 50): [CS8618] Non-nullable property 'L' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Solution

  • As Blazor will always assign the property to a non-null value before executing your code, it is safe to disable the warning using = default!.

    [Inject] private IStringLocalizer<Element> L { get; set; } = default!;