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.
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!;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With