Safe navigation of indexed objects

With the introduction of Roslyn, C # takes advantage of the safe navigation operator. This is great for objects that use dot notation, for example.

MyClass myClass = null;
var singleElement = myClass?.ArrayOfStrings[0];

      

In this case, myClass is null, but the safe operator keeps me out of the exception.  

My question is, do you have an indexed object equivalent to a safe navigator implementation? An example of this should look like this:

var myClass2 = new MyClass { ArrayOfStrings = null };
var singleElement2 = myClass2?.ArrayOfStrings[0];

      

In this case, myClass2 is not null, but the ArrayOfStrings property, so when I try to access it, it throws an exception. Since there is no dot notation between ArrayOfStrings and the index, I cannot add a safe navigator.  

Since it is an array, I can use the safe nav operator as follows, but that doesn't work for other collections like Lists and DataRows

var myClass3 = new MyClass { ArrayOfStrings = null };
var singleElement3 = myClass3?.ArrayOfStrings?.GetValue(0);

      

+3


source to share


1 answer


Based on the language characteristics status page it looks like this:

var singleElement2 = myClass2?.ArrayOfStrings?[0];

      

Example on page:



customer?.Orders?[5]?.$price

      

... Admittedly, some have $price

been stripped now, I suppose, but I expect indexed zero propagation to work.

+8


source







All Articles