Null conditional and Null Coalescing operator in c-sharp

Author : Sachin Sharma
Published On : 01 May 2023
Tags: c# dotnet-core

In C# ? and ?? both operator is used to handle NULL values but there is some difference between them.Here will see how to use it with example.

? operator is called the Null conditional operator. this is used to handle null value of object and allow acess of members of object reference

and incase of null object reference it return null instead of Null reference exception.

Example of using the Null conditional operator

string name = employee?.Name;

This code return value like employee.Name if the employee object reference is null then it return null otherwise return employee.Name

the ?? operator is called the Null Coalescing Operator it provice default value for the nullable value of type.

Example of using the null coalescing operator

int age = person?.Age ?? 0;   

The code assign person.Age value to age variable but if person is not null. if person is null and age variable is null or person is not null and age is null it assign default value 0 to age variable.

 

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.

 

 

Comments

No comments have been added to this article.

Add Comment