C# 6 features – Null-conditional (?. and ?[]) and null-coalescing (??) operators


facebooktwittergoogle_pluslinkedinmail

Don’t you have a feeling that sometimes C# code goes too much in null-checking? Yep, me too. But there are few C# 6 null-conditional operators that change it for good.

 

Null-conditional / Elvis operator – ?.

Let’s start with null-conditional operator – it’s  ?.. It’s also called ‘elvis-operator’. Not sure why? Have a closer look – you will see a pair of eyes with elivs like haircut. The operator lets you access members and elements only when the receiver is not-null, returning null result otherwise.

int? length = people?.Length; // null if people is null

The above is more less equivalent to:

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

Except that people variable is only evaluated once. So it’s more like:

var tempVariable = people;
int? length = (tempVariable != null) ? (int?)tempVariable.Length : null;

 

Second null-conditional operator – ?[]

There is also second null-conditional operator that lets you access elements by index operator.

Person first = people?[0];              // null if people is null
Type personType = people?[0].GetType(); // null if people is null

You can also chain null-conditional operators.

int? count = customers?[0].Orders?.Count();

 

Null-coalescing operator – ??

The null-coalescing operator was designed to be used easy with null-conditional operators. It provides default value when the outcome is null.

int length = people?.Length ?? 0; // 0 if people is null

 

Null-conditional delegate invocation

Delegate invocation can’t immediately follow the ? operator – too many syntactic ambiguities. Following will not work:

if (myDelegate?(args) ?? false) { … } // Won’t compile!

However, you can call it via the Invoke method on the delegate:

if (myDelegate?.Invoke(args) ?? false) { … } // Will work fine

Very useful way to use it is for event triggering.

PropertyChanged?.Invoke(this, args);

Note it’s thread-safe way to check for null as the left-hand side is evaluated only once.

 

facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *