With the introduction of Roslyn, C# gets the benefit of the Safe Navigation operator. This is brilliant for objects that use dot notations e.g.
MyClass myClass = null;
var singleElement = myClass?.ArrayOfStrings[0];
In this instance myClass is null but the safe operator saves me from the exception.
My question is if you have an indexed object is there an equivalent implementation of the safe navigation operator? An example of needing this would look like this:
var myClass2 = new MyClass { ArrayOfStrings = null };
var singleElement2 = myClass2?.ArrayOfStrings[0];
In this instance myClass2 is not null but the ArrayOfStrings property is, so when I try and access it it will throw an exception. Because there is no dot notation between ArrayOfStrings and the index I can't add the safe nav operator.
Because this is an array I can use the safe nav operator in the following way, but this doesn't work for other collections such as Lists and DataRows
var myClass3 = new MyClass { ArrayOfStrings = null };
var singleElement3 = myClass3?.ArrayOfStrings?.GetValue(0);
It is used to avoid sequential explicit null checks and assignments and replace them with method/property chaining.
The Angular safe navigation operator, ? , guards against null and undefined values in property paths. Here, it protects against a view render failure if item is null .
Use the safe navigation operator ( ?. ) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.
Based on the Language Feature Status Page it looks like you want:
var singleElement2 = myClass2?.ArrayOfStrings?[0];
The example on the page is:
customer?.Orders?[5]?.$price
... admittedly the $price
part has been withdrawn now, I believe, but I would expect the indexed null propagation to work.
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