#1,202 – C# 6.0 – Null-Conditional Operator

One of the new features coming in C# 6.0 is the null-conditional operator.

If you have a reference-typed variable, it can have a null value or can refer to instance of the appropriate type.  You’ll often see the following pattern, checking for null before invoking a method on the object, to avoid a NullReferenceException.

            string sTest = DateTime.Now.Hour == 5 ? "Five" : null;

            // OLD: Check for null to avoid NullReferenceException
            string sLeft;
            if (sTest != null)
                sLeft = sTest.Substring(0, 1);

The null-conditional operator allows us to do the same check for null, but in a more concise manner.

            // NEW: Null-Conditional operator
            sLeft = sTest?.Substring(0, 1);

If sTest is non-null, the Substring method is called and the result is assigned to sLeft.  If sTest is null, the expression returns null, so a null value is assigned to sLeft.