1 minute read

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.

Note: C# 8.0 adds Nullable Reference Types which can remove the the risk of NullReferenceException. You can enable the null reference analysis at project level

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);

Tags: ,