Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null propagation operator and foreach

Reading a lot about the Null propagation operator ?., I found no answer whether it is helpful in the following scenario.

Code that throws:

int[] values = null;

foreach ( var i in values ) // Throws since values is null.
{
    // ...
}

To make this working, I have to add a null check before access to the values variable.

Most likely the above code is out of scope of the design considerations for the Null propagation operator. Still, to be sure, I have to ask.

My question:

Is the Null propagation operator helpful when trying to access null collections in a foreach loop?

like image 725
Uwe Keim Avatar asked Dec 30 '14 10:12

Uwe Keim


People also ask

What is null propagation?

Starting from version 6.0, C# supports a shorter notation, the null conditional operator. It allows checking one or more expressions for null in a call chain, which is called null propagation. Such a notation can be written in a single line whereas a number of if-else statements typically occupy many lines.

What is null conditional and null coalescing?

Similar to the coalescing operator, the null conditional operator tests for null before accessing a member of an instance. First example. The null coalescing operator is useful inside properties. Often, a property that returns an object (such as a string) may be null.


1 Answers

I've found another, working way:

When using Jon Skeet's (et al) fantastic MoreLinq extensions, there is a ForEach extension method which I can use in my initial example like:

int[] values = null;

values?.ForEach(i=> /*...*/); // Does not throw, even values is null.
like image 66
Uwe Keim Avatar answered Nov 11 '22 15:11

Uwe Keim