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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With