Null-Conditional Operator in C# 6

Null-Conditional Operator in C# 6

I've already mentioned a couple new features in C# 6: Auto-Property Initializers and String Interpolation. Another new feature introduced in C# 6 is the null-conditional operator, which helps us avoid verbose null reference checks and offers optional chaining.

Null-Conditional Operator in C#

The null-conditional operator in C# 6 helps you with those verbose null reference checks. For example if you want to generate a quick summary of an item by truncating the description you may need to first check if the description is null before using various string methods. This avoids the dreaded null reference exception that could occur if description is null.

if (description != null) {
    summary = description.Substring
         (0, Math.Min(description.Length, 255));
}

You can avoid that null check by using the new null-conditional operator in C#, which immediately returns null and avoids the Substring call if description is null. Two lines of code become one. Notice the addition of the "?" after the variable "description".

summary = description?.Substring
     (0, Math.Min(description.Length, 255));

Using the null-conditional operator with the null coalescing operator makes it a lot easier to obtain the length of the variable "description", too, should it be null. Everything comes down to a single line of code again.

int length = description?.Length ?? 0;

Optional Chaining

The new Swift Programming Language has this null-conditional operator, too, but it is referred to as Optional Chaining, which might help in the way we think about the null-conditional operator. In the following example we want the FAX number for a customer.

var fax = customer?.ShippingAddress?.Fax;

The path from customer to ShippingAddress is considered optional by way of the null-conditional operator. If the customer is null, do not continue and just return null. If customer is not null, continue on. Once again, the path from ShippingAddress to Fax is optional. If ShippingAddress is null, do not continue and just return null, otherwise return the Fax. Hence the null-conditional operator can be thought of as optional chaining.