Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe Navigation of indexed objects

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);
like image 250
rh072005 Avatar asked Sep 04 '14 16:09

rh072005


People also ask

What is the purpose of the safe navigation operator?

It is used to avoid sequential explicit null checks and assignments and replace them with method/property chaining.

What is safe navigation operator in angular?

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 .

What does safe navigation operator return?

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.


1 Answers

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.

like image 79
Jon Skeet Avatar answered Oct 09 '22 10:10

Jon Skeet