Last week I had the need to have a link that points to a news results page, a page that shows all the news articles on a page. This blog is to remind me how to use the null-coalescing operator and I hope it's useful to others.
To illustrate this, the link looks like :
In the back office, on the site root node, there is a Multi Url Picker which has a max number of nodes allow to select set to 1.
var rootNode = Model.Root<SiteRoot>();
var newsListingPage = rootNode.NewsResultsPage ?? rootNode.FirstChild<NewsListing>();
Then within the view I can then do
<a href="newsListingPage.Url()">All news</a>
The null-coalescing operator ??
returns the value of its left-hand operand if it isn't null
; otherwise, it evaluates the right-hand operand and returns its result. The ??
operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null. - Microsoft Docs
So I check to see if the rootnode.NewsResultsPage has a value e.g. has the user selected a news listing node?
If a user doesn't select a news node it falls back to finding the first child node that has a type "NewsListing".
If there is no News Listing node found then I hide a load of html with a null check.
if(newsListingPage != null)
{
...
}
Published on: 20 February 2022