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


Facebooktwitterlinkedinmail

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.

 

Facebooktwitterlinkedinmail

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

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

  • Eric Teutsch

    Nice. Just verified that

    PropertyChanged?.Invoke(this, new EventArgs(args));

    only creates the EventArgs object if PropertyChanged is not null.

    • Mariusz Bojkowski Post author

      It will be equivalent to something like this:

      var tempPeople = people; // Get 'people' value only once
      if (tempPeople is null) { personType = null; }
      else
      {
      var tempItem = tempPeople[0]; // Get 'people[0]' value only once
      if (tempItem is null) { personType = null; }
      else { personType = tempItem.GetType(); }
      }

  • Micah Epps

    In your event triggering example. The null conditional operator isn’t thread safe. Meaning, if another thread unsubscribes from you event between the evaluation and invocation stages, then the invoke will be called on a null value. NullReferenceException.

  • ET

    It’s called the Elvis operator because the Visual Studio team long ago adopted persona names for the VB, C#, and C++ developers (this was circa 2000 for v1). The C# persona was named Elvis. C++ persona was Einstein. and so on

    • ET Iswrong

      This is absolutely untrue. It’s called the Elvis operator due to its history related to the ?: operator, which supposedly looks like Elvis Presley’s hair sideways.

  • Rafał

    Thank you for your article. I’m fairly new in c# and I’m afraid I don’t understand one thing:
    int? length = people?.Length
    When should I use Null-conditional / Elvis operator? Is it a good practice to write a code which doesn’t check if people are null and throw loud exception like “Something is wrong because people are null”?

    I’ve heard that type of application/program should always be in a valid state – in the state that we expected.

    • Mariusz Bojkowski Post author

      Hi,

      In general, it’s good practice to write code that is null-safe. But from experience, I know that many people don’t do it.

      Regards,
      Mariusz