Null Conditional Operator And Null Coalescing Operator

Introduction

In ASP.NET Core (and in C# in general), the ? and ?? operators are both used to handle null values, but they have different functionalities.

The ? operator is called the Null Conditional Operator, and it allows you to safely access members of an object reference that might be null. It checks if the object reference is null before attempting to access its members, and if the object reference is null, it returns null instead of throwing a null reference exception.

Example of using the null conditional operator,

string name = person?.Name;

This code assigns the value of person.Name to the name variable, but only if the person object is not null. If the person object is null, the name variable will be assigned a null value.

the ?? operator is called the Null Coalescing Operator, and it allows you to provide a default value for a nullable type or a null value. It checks if the left operand is null, and if it is, it returns the right operand. If the left operand is not null, the operator returns its value.

Example of using the null coalescing operator,

int age = person?.Age ?? 0;

This code assigns the value of person.Age to the age variable, but only if the person object is not null. If the person object is null or person.Age is null, the age variable will be assigned a default value of 0.

public IActionResult Index() {
    Person person = GetPerson();
    string name = person?.Name; // null conditional operator:
    int age = person?.Age ?? 0; // null coalescing operator:
    ViewBag.Name = name;
    ViewBag.Age = age;
    return View();
}

Summary

The ? operator is used to safely access members of an object reference that might be null, while the ?? operator is used to provide a default value for a nullable type or a null value.

Thank you for reading, and I hope this blog post has helped provide you with a better understanding of  Null Conditional Operator and  Null Coalescing operator.

Next Recommended Reading Implicit Operator in C#