Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 395
Taco Avatar asked Jun 06 '26 22:06

Taco


2 Answers

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!;
like image 103
meziantou Avatar answered Jun 10 '26 17:06

meziantou


I had similar problems when I first moved over to Nullable.

The Inject issue can be resolved like this:

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

You can use the null forgiving ! operator where you know the object won't be null, or the null coalescing operator to check for null and return a default value.

private string? value;
private bool hasValue => value is not null;

string SomeMethod()
{
  return hasValue
    ? value!
    : string.empty;
}

//or 

string SomeOtherMethod()
{
  return value ?? string.empty;
}
like image 22
MrC aka Shaun Curtis Avatar answered Jun 10 '26 17:06

MrC aka Shaun Curtis