#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: