Null Conditional Operator In C#

In this blog, you will learn about Null Conditional Operator ?. in C#.

Null Conditional Operator ?. is introduced in C# 6.0. It will return null if the left-hand side expression is evaluated to null instead of throwing an exception (NullReferenceException).  If the left-hand side expression evaluates to a nonnull value then it will be treated as a normal .(dot) operator and it might return null because its return type is always a nullable type means that for a struct or primitive type it is wrapped into a Nullable<T>.

var id = Emp.GetEmpId()?.Value; // This will returns null if GetEmpId() returns null.
var empId= Emp.GetEmpId()?.IntegerValue; // Here empId will be of type Nullable<int>, that is int?

This comes convenient when firing events, normally we invoke an event inside the if condition by null checking so it will introduce a race condition. Using Null Conditional Operator we can fix as below,

event EventHandler<string> RaiseEvent;
RaiseEvent?.Invoke("Event raised");

Below is an example of using a Null Conditional Operator,

using System;
namespace NullConditionalOperator {
    class Program {
        static void Main(string[] args) {
            Employee emp = null;
            GetEmpDetails(emp);
            emp = new Employee() {
                FirstName = "Rajanikant", LastName = "Hawaldar"
            };
            GetEmpDetails(emp);
            Console.ReadKey();
        }
        public static void GetEmpDetails(Employee emp) {
            Console.WriteLine("Employee Details:");
            Console.WriteLine(emp?.FirstName); //use ?. operator 
            Console.WriteLine(emp?.LastName); // use ?. operator
        }
    }
    public class Employee {
        public int EmpId {
            get;
            set;
        }
        public string FirstName {
            get;
            set;
        }
        public string LastName {
            get;
            set;
        }
    }
}

Summary

In this blog, we learned Null Conditional Operator with an example.