Null Coalescing operator in C-Sharp

Updated on: June 10, 2021
  • It is used to pass default value if variable is null.

  • It is used for both value type and reference type variable.

  • It is used to avoid multiple if condition for checking null and returning non null value

In the following example value x is of value type is marked as nullable type and null value is assigned to variable “x”, while assigning value “x” to variable “y” we have checked for x is equal to null, if it is null then assign “100” or else assign value of “x”.

Value Type Example : 

int? x = null;

 int y = x ?? 100;

Console.WriteLine("y : " + y);

Output of the above program : 

Reference Type Example : 

In the following example value “selectedProduct ” is of refference type is marked as nullable type and null value is assigned to variable “selectedProduct ”, while assigning value “selectedProduct ” to variable “defaultProduct ” we have checked for selectedProduct is equal to null, if it is null then assign “Laptop” or else assign value of “selectedProduct”.

string selectedProduct = null;

string defaultProduct = selectedProduct ?? "Laptop";

Console.WriteLine("Product is : " + defaultProduct);