Null conditional operator (?.) is another useful addition made to C# 6.0, it allows developers to write cleaner and concise code. We will explore more in detail.

In some situations, whenever you access a method or property on object that is null then it throws a Null Reference exception. These exceptions can be difficult to track down and fix, especially in large codebases

The Null-Conditional Operator, represented by ?., provides a elegant solution to this problem. It allows developers to safely access members of an object without worrying about null references.

This operator (?.) verifies nullability of the operand before calling the method or property.

Syntax and usage of null conditional operator (?.) :

Null conditional operator uses a question mark and member access operator . (the dot) as follows.

expression1 ?. expression2  (This expression evaluates to expression2, if expression1 is Not-Null. else, it evaluates to null.)

If the object on which the operator is applied is null, the expression evaluates to null instead of throwing an exception.

Example -1

Let’s look at below example, here we have declared an Employee class, in the main program we have created an emp object and trying to access its property by doing a null check using (Conditional operator (?:)

namespace NullConditionalOperator
{ 
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }    
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = null;

            //If employee is not null then return emp.Name else set null
            string empName = (emp != null) ? emp.Name : null;
        }
    }
}

In the above example,

  • This line string empName = (emp != null) ? emp.Name : null; evaluates as, If emp is not null then assign emp.Name value to empName else assign null.
  • If you run above example then null value will be assigned to empName .

Let’s, re-write above statements using null-conditional operator (?.) as follows.

namespace NullConditionalOperator
{   
     public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = null;

            //If employee is not null then return employee Name else null.
            //Use of null conditional operator
            string empName = emp?.Name;
        }
    }
}

In the above example,

  • We are using null-conditional operator(?.) to replace that extra null check condition.
  • This code statement empName = emp?.Name; evaluates as, If emp object is not null then invoke the property and assign emp.Name value to empName variable else assign null.

The usage of null-conditional operator (?.) here allows cleaner and concise code and also removed extra null conditional check. 

Example -2

In below example, we have created an Employee instance as emp and set emp.Name property value to “John” and emp.Age property value to 45. We have set emp.PresentAddress property value to null.

using System;
namespace NullConditionalOperator
{
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Address PresentAddress { get; set; }
    }
    public class Address
    {
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string Zip { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee(); 
            emp.Name = "John";
            emp.Age = 45;
            emp.PresentAddress = null;

            Console.WriteLine("Employee Details");
            Console.WriteLine("");
            Console.WriteLine("Name : {0}", emp?.Name); //
            Console.WriteLine("Age  : {0}", emp?.Age);
            Console.WriteLine("");
            Console.WriteLine("Employee Address");
            Console.WriteLine("");
            Console.WriteLine("City    : {0}", emp?.PresentAddress?.City);
            Console.WriteLine("State   : {0}", emp?.PresentAddress?.State);
            Console.WriteLine("Country : {0}", emp?.PresentAddress?.Country);
            Console.WriteLine("Zip     : {0}", emp?.PresentAddress?.Zip);

            Console.Read();
        }
    }
}

When we run above sample code it will generate below output.

Null-Conditional_Operator_1.3

You can see in the output window; we are able to fetch Name and Age property value correctly. However, Address properties are displayed as empty.

Let’s see why this happened here. 

  • We created a new Employee instance Employee emp = new Employee(); and assigned values to Name and Age properties.
  • One thing you note here is that the emp object is not null, that’s why emp?.Name and emp?.Age evaluated to valid values.
  • In case of emp.PresentAddress , even though emp object is not null, but since we have set emp.PresentAddress = null , therefor the address properties emp?.PresentAddress?.City , emp?.PresentAddress?.State , emp?.PresentAddress?.Country and emp?.PresentAddress?.Zip weren’t evaluated and set to default empty value. 

Key Points to be noted:

Below points should be noted while using this operator (?.)

  • When you access an object property that returns value type, in that case null conditional operator (?.) will return nullable version of that type.

For example, In below case, Age property is a value type and emp?.Age returns int? (nullable type of int ) and not an int . So while assigning it to a variable then you have to declare the variable as nullable type. In below case we have declared int? employeeAge as Nullable type.

Null-conditional_Operator_1.0

It throws a compile error if you don’t specify the nullable type.

Null-conditional operator
  • You can chain multiple null conditional operator (?.) in an expression, If the first operand is null, then the expression evaluation is short-circuited, and no further invocation within the call chain occurs. 

For example,  when we invoke emp?.PresentAddress?.State; in below example code, then both PresentAddress and State property will be invoked only if emp is Not null. If emp is nullthen no further call in the expression will occur.

namespace NullConditionalOperator 
{  
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = null;

            //Chain invocation using old way.
            //If emp is null, return null else if employee address is null return null, else return employee state
            string state = (emp == null) ? null : (emp.PresentAddress == null) ? null : emp.PresentAddress.State;

            //Chain invocation using null-conditional operator
            //if emp is not null and address is not null then return state else return null 
            string employeeState = emp?.PresentAddress?.State;            
        }
    }
}

Use of Null-Conditional Operator(?.) with Member Access operator (.)

If you club null conditional operator (?.) and member access operator (.) together, then during assignment expression the resulting expression will return null, if the left operand evaluates to null. However, it will throw a Null Reference Exception if the left operand of (?.) evaluates to null.

For example: emp?.PresentAddress.State returns null when emp object is null. However, emp.PresentAddress?.State throws a Null Reference Exception when emp object is null.

Conclusion:

The Null-Conditional Operator in C# is a powerful tool that can make your code safer, cleaner, and easier to maintain. 

Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on Null Coalescing Operator (??) in C#  and  Conditional Operator in C# (?.)