DEV Community

Owain Williams
Owain Williams

Posted on • Originally published at owain.codes on

Null Conditional Operator for fallback images

Generic Header image

Last night when working on my new version of Owain.Codes I managed to blow up the site.

The reason?

I hadn't put an image in to the CMS and when I rendered out the image or the lack of an image on the front end, I got a null exception error.

I started to write a bit of code to handle this which looked a bit like

@if(Model.Image.Url() == null)
{
  set default image as fallback.jpg
}
else{
  use the image from the CMS
}
Enter fullscreen mode Exit fullscreen mode

But then I thought, there must be a nicer way to handle fallbacks, and I believe I have found that nicer option and its by using the Null Conditional Operator

So I am now using:

 var blogImage = Model.PageBanner?.Url() ?? "assets/images/noImage.jpg";
Enter fullscreen mode Exit fullscreen mode

So if the Model.PageBanner is null, give me the noImage.jpg fall back string, else give me the Model.PageBanner.Url(). I then use the variable blogImage on my page.

I now don't need to worry about whether I set an image for a blog or not. Either way I will have an image on my page.

Top comments (2)

Collapse
 
lexlohr profile image
Alex Lohr

In this case, it would be sensible to replace the nullish coalescing operator with a logical or ||, as any falsy value (for example an empty string or the number zero) will not make for a valid URL.

Collapse
 
owainwilliams profile image
Owain Williams

Thanks Alex, that's really helpful. I'll be sure to keep this in mind and update my own code to reflect the suggestion.