C# Null Coalescing (??) Operator

Updated on     Kisan Patel

The null coalescing operator ?? is mostly used with the nullable value types and reference types.

int? i = null; // Declare nullable type variable
int k;
 
k = i ?? 5; // null coalescing operator

The ?? operator is used between two operands where the first operand must be a nullable type. The second operand must be of the same type as the first operand or of the type that can be implicitly converted to the first type. It checks whether the value of the first operand is null or not. If the value of the first operand is null, it returns the value of the second operand.

In case, if you declare the second operand to the type that cannot be implicitly converted to the type of the first operand, a compile-time error is generated.

Let’s take one example to understand the concept of ?? operator more clearly.

class Program
{
      public static void Main(string[] args)
      {
           int? i = null; // Declare nullable type variable
           int? j = 20;
           int k;
 
           k = i ?? 5;
 
           Console.WriteLine("The value of k is " + k);

           k = j ?? 10;
           Console.WriteLine("Now the value of k is " + k);

           Console.ReadLine();
      }
}

the output of the above C# program…

null-coalescing-operator


C#

Leave a Reply