Do you ever get tired of writing code like this?
if (listOfStrings != null)
{
foreach (string item in listOfStrings)
{ ... }
}
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>())
{ ... }
Lots more in the official docs from Microsoft
Latest comments (2)
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.
My personal preference for more readable code would be to adopt a 'happy path' and return from the method before reaching the loop.
A good article on adopting the happy path
Write better code and be a better programmer by NEVER USING ELSE statements
Douglas Parsons ・ Nov 10 '20 ・ 5 min read