How to use Null Conditional operators

Null values are very special in any language, specifically in C#. Every .NET developer must have pulled his/her hair at some point or other while dealing with it. C# is getting mature by adding more capabilities to handle the null values so that we don’t need to write long repetitive code to handle it. This operator was introduced with C# 6.0 sometimes also referred as safe navigation operator, and can be panacea for the most common NullReferenceException. There are few related topics like Null Coalescing operator, Nullable types, which I will advise to take a quick look before proceeding.

What is Null Conditional Operator?

This is a new operator introduced with C# 6.0, helps in performing null check while accessing its members. It provides following two syntax

  1. First operator: ?.   (Also called elvis operator)
  2. Second operator: ?[

Let’s see it with examples

First Null Conditional Operator (?.):

This operator allows us to access the members or elements of the provided instance only when it is not null. So before moving further, lets create few classes for the example

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

    public List <Address> Addresses { get; set;}

    public Person Spouse {get; set;}
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string Zip { get; set; }
}

If you have to access properties of the person, the usual way of doing it

if(p != null)
{
    string name = p.FirstName;
    int age = p.Age;
}

Now lets see using the ?. operator

string name = p?.FirstName;
int? age = p?.Age;

Here we dont need to have a null check as it is taken care by the null conditional operator. name is assigned to null if either object p is null or FirstName is null. While for age, I had to change the age variable as Nullable type because for value types, this operator returns a nullable type which is easily understandable as it would have no value (or null) if p is null.

Now if want to access the properties of Spouse then normally code would be as

if(p != null && p.Spouse != null)
{
    string name = p.Spouse.FirstName;
    int age = p.Spouse.Age;
}

which can be written as

string name = p?.Spouse?.FirstName;
int? Age = p?.Spouse?.Age;

Here, we avoided two null check and code looks much cleaner and concise. This operators becomes more helpful for the descending types. You must have written similar code like below numerous times while handling a service response

if (response != null && response.Results != null && response.Results.Status == Status.Success)
{
    // Handle response
}

this can be as

if (response?.Results?.Status == Status.Success)
{
        // Handle response
}

It looks super clean now. It could be more granular based on the scenario. Now let’s see another operator.

Second Null Conditional Operator (?[): This operator allows you to have a check over index operator. Let’s see the example.
Here I want to see the city of the second address of the person so normally, we will write it as

if(p!=null && p.Addresses != null && p.Addresses.Count > 1)
{
    string city = p.Addresses[1].City;
}

This we can write now as

string city = p?.Addresses?[1]?.City;

Now you can assume if I have read the same for spouse then how consize code would be.

Other Usages:
It can be used while calling method of instance like

p?.ToString();

We can use it with delegate and events as well like

myCustomDelegate?.Invoke(args)

// Note : myCustomDelegate?(args) won't work and it will be an compile time error

myCustomEvent?.Invoke(this, args);

I found this feature very useful in our day to day coding as we save lot of repetitive code. Hope you find it useful as well.

Cheers,
Brij

Leave a comment