What does the two question marks together (??) mean in C#?

CsharpServer Side ProgrammingProgramming

It is the null-coalescing operator. The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the lefthand operand evaluates to non-null.

A nullable type can represent a value that can be undefined or from the type's domain. We can use the ?? operator to return an appropriate value when the left operand has a nullable type. If we try to assign a nullable value type to a non-nullable value type without using the ?? operator, we will get a compile-time error and if we forcefully cast it, an InvalidOperationException exception will be thrown.

The following are the advantages of the Null-Coalescing Operator (??) operator −

  • It is used to define a default value for a nullable item (for both value types and reference types).

  • It prevents the runtime InvalidOperationException exception.

  • It helps us to remove many redundant "if" conditions.

  • It works for both reference types and value types.

  • The code becomes well-organized and readable.

Example

 Live Demo

using System;
namespace MyApplication{
   class Program{
      static void Main(string[] args){
         int? value1 = null;
         int value2 = value1 ?? 99;
         Console.WriteLine("Value2: " + value2);
         string testString = "Null Coalescing";
         string resultString = testString ?? "Original string is null";
         Console.WriteLine("The value of result message is: " + resultString);
      }
   }
}

Output

The output of the above example is as follows.

Value2: 99
The value of result message is: Null Coalescing
raja
Updated on 04-Aug-2020 06:37:56

Advertisements