#1,203 – C# 6.0 – Using the Null-Conditional with Value Types

The new null-conditional allows checking for null and de-referencing a reference-typed variable in a single step.

            string sLeft = sTest?.Substring(0, 1);

If the variable being checked for null (e.g. sTest) is null, the result of the expression is null.  This works as expected if the result of the expression is being assigned to a reference-typed variable (e.g. sLeft).  If the method or property being invoked, however, is a value type, then the result of the expression must be a nullable type.

For example, we might do the following in C# 5.0:

            int sLen;
            if (sTest != null)
                sLen = sTest.Length;

If sTest is null, the assignment isn’t done and sLen retains its value.

In C# 6.0, you can do this assignment using the null-conditional.  The variable being assigned to must be a nullable type whose base type matches the type of the expression.

            int? sLen = sTest?.Length;