The Null conditional operator is another cool little feature that C# 6.0 ships with. It eases null checking behavior by simplifying the amount of code to be written.

Here is an example of the usual (old way) null checking behavior:

if (dataList != null) 
    // Other Stuff.. 

It might not look that bad at first but sometimes code drowns in these null checks. Below is what we can do with the new null conditional operator.

C# 6.0 – Null conditional operator

With the new null conditional operator here is the above example re-written.

dataList?.Add(data); // Other Stuff..

It’s very simple and furthermore it can be nicely used with the null coalescing operator like so:

int length = users?.Length ?? 0;

This essentially corresponds to:

int length = (users != null) ? users.Length : 0;

As a final note, the null conditional operator models short-circuiting behavior. This means that if users is null then the following member or element accesses won’t happen.

A summary of the null conditional operator:

  • Return null if the operand is null.
  • Short-circuit additional invocations in the call chain if the operand is null.
  • Return a nullable type (System.Nullable) if the target member returns a value type.
  • Support delegate invocation in a thread safe manner.
  • Is available as both a member operator (?.) and an index operator (?[…]).

That’s it for now!