Home > Net >  blazor best nullcheck in razor / html?
blazor best nullcheck in razor / html?

Time:10-20

lets say that i have

class foo
{
  public List<string> Values {get;set;}=New()
}

and in component

foo? bar;

protected override async Task OnInitializedAsync()
 {
         bar= await _ds.Get<foo>();
 }

so now in razor is there any other / better way for nullcheck ?

@if (bar!= null)@foreach(var x in bar.Values)
  {
        <MudSelectItem  Value="x">@x</MudSelectItem>
   }

best would be something like

 @foreachWhenNotnull(var x in bar.Values)...

i known that i can do like a component that will do that this but maybe it is simplest way ?

thanks and regards

CodePudding user response:

It is better to check whether it is null or not like in your own code, because based on whether it is null or not, you can decide, for example, to display an error or a message. But if you just want to avoid getting a System.NullReferenceException error, you can do the following

use null conditional operators

@foreach (var x in bar?.Values ?? new())
{
   <MudSelectItem Value="x">@x</MudSelectItem>
}

You can do it this way too :

foo bar;

protected override async Task OnInitializedAsync()
{
    bar = (await _ds.Get<foo>()) ?? new();
}
  • Related