Chained null checks

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /var/www/ on line 524

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

Null-conditional operators is one of the features in C# 6 that will save the world from a lot of boilerplate code and a bunch of NullReferenceExceptions. It works as chained null checks!

Console.WriteLine(person?.HomeAddress?.City ?? "City unknown");

Note the null-conditional operator (?.) after person and HomeAddress, it returns null and terminates the object reference chain, if one of the references are null.

It is the same logic as the below code that you can use today.

if (person != null)
    person.HomeAddress != null)
  Console.WriteLine("City unknown");

The null-conditional operator will also make it easier to trigger events. Today it is required to reference the event, check if it is null before raising the event like so.

protected void OnPropertyChanged(string name)
  PropertyChangedEventHandler handler = PropertyChanged;

  if (handler != null)
    handler(this, new PropertyChangedEventArgs(name));

But the null-conditional operator provides a tread-safe way of checking for null before triggering the event.

PropertyChanged?.Invoke(this, args);