#1,204 – C# 6.0 – Using Null-Conditional with Indexer

The new null-conditional operator in C# 6.0 allows checking for null and de-referencing a variable in a single step.

You can use the null-conditional operator with dot (.) notation, to access an object’s properties or to invoke a method.  You can also use the null-conditional with an indexer, as shown below.  The expression returns the value returned by the indexer if the variable is non-null, or returns null if the variable is null.

            string sTest = "Howdy";

            char? thirdChar = sTest?[2];   // 'w'

            sTest = null;
            thirdChar = sTest?[2];   // null

            sTest = "Ho";
            thirdChar = sTest?[2];   // throws IndexOutOfRangeException

Notice that the null-conditional operator protects you from de-referencing a null pointer, but does not protect you from using an index that is longer than the string length.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,204 – C# 6.0 – Using Null-Conditional with Indexer

  1. Pingback: Dew Drop – October 15, 2014 (#1877) | Morning Dew

Leave a comment