DEV Community

loading...

Simplify foreach loops with the null-coalescing operator

twwilliams profile image Tommy Williams ・1 min read

Do you ever get tired of writing code like this?

if (listOfStrings != null)
{
    foreach (string item in listOfStrings)
    { ... }
}
Enter fullscreen mode Exit fullscreen mode

Wouldn't it be nice if the foreach loop automatically checked for null and skipped the loop the same way it does when there are no items?

Here's where the null-coalescing operator can help:

foreach (string item in listOfStrings ?? Enumerable.Empty<string>())
{ ... }
Enter fullscreen mode Exit fullscreen mode

Lots more in the official docs from Microsoft

Discussion (2)

pic
Editor guide
Collapse
devguyky profile image
devguyky

My personal preference for more readable code would be to adopt a 'happy path' and return from the method before reaching the loop.

if (listOfStrings is null)
   return;

foreach (string item in listOfStrings)
{ ... }
Enter fullscreen mode Exit fullscreen mode

A good article on adopting the happy path

Collapse
jayjeckel profile image
Jay Jeckel

It's a neat trick, but all I can see when looking at it is an unnecessary allocation. I guess it comes down to which one finds more annoying, writing an if statement one time or burning extra cpu and memory every time the line of code is run.