INTRODUCTION: Let’s take a poll… As a developer, what keeps you on your toes, yet mind-numbingly bored at the same time? For me, it’s null reference checking. I know I’m not alone and that it’s such a pervasive problem that Microsoft decided to do something about it. Welcome to the enlightened world of Null Propagation.

Null Propagation is a new feature in C# 6 that allows you to chain together nullable operations into a single chain that short-circuits on the first null reference, without worrying about having to check the whole chain for null references.

This is one of the most impressive solutions to the mess that arises from continuously nested null reference checks. Let’s look at some code.

EXAMPLE 1

string oops = null;
oops = MethodThatMayReturnNull();
if(oops != null)
{
    // Assume an extension method on String.  **
    oops.MethodThatProcessesOopsThatMayReturnNull(someOtherValue);

    if(oops != null)
    {
        // You get the picture...
    }
}

** (see: This Article)

What a mess!

EXAMPLE 2

string oops = MethodThatMayReturnNull()?.MethodThatProcessesOopsThatMayReturnNull(someOtherValue); // Just keep chaining!

Where’s the Null Reference checks? See that ? between methods? It means that the second method will be called only if the first method does NOT return a null value. If it does return a null value, then the call chain is broken and oops contains a null. That’s when you test for null: when it actually means something semantically to the application.

One of the most common usages of Null Propagation is calling events. Turn 4 lines of code into 1!

// Old way
if(eventDeclaration != null)
{
    eventDeclaration(this, EventArgs.Empty);
}

// The Null Propagation Way
eventDeclaration?.Invoke(this, EventArgs.Empty);

CONCLUSION: I love C# 6! This is a game changer. You write better code that is both easier to read, and more reliable (admit it, how many times have you neglected that Null Reference Check because you were certain you’d never have a Null Reference. How’d that work for ya?) Now, with Null Propagation, there’s no excuse for writing code that doesn’t use proper Null Reference checking because your Null Reference checks are only needed for business logic, not boilerplate.