Null Coalescing operator Examples and Tutorials | C# Double question marks

This tutorial explains double question marks(??), also null-coalescing operator tutorials with examples.

It is an operator introduced in language specification to solve the problem.

Commonly, the condition is used to check whether a variable is null or not. The below program checks the given string is not null, assigns it to the result variable, or else returns the default value to it.

using System;

public class Program {
  public static void Main() {
    var result = "";
    String str = null;
    //Null Check
    if (str != null)
      result = str;
    else
      result = "empty";

    Console.WriteLine(result);

  }
}

To simplify the if null check, the ternary operator is used to reduce the code and readability.

using System;
public class Program
{
	public static void Main()
	{
		var result="";
		String str =null;
		result=(str != null)? str: "default"; //ternary Operator
		Console.WriteLine(result);
	}
}

Do you still improve the existing code, yes:point_right: yes, C# introduced Null coalescing Operator(??) to solve code readability and concise way.

C# Null coalescing Operator Example

Null coalescing Operator alias double question marks allows handing default values in C# programming Syntax

operand1 ?? Operand2

It is a Binary and short circuit operator that operates on two operands.

This operator returns

  • Operand1 value returned if operand1 is not null, undefined.
  • Operand2 value returned if operand1 is null or undefined.

Here is an example

using System;

public class Program {
  public static void Main() {
    var result = "";
    String str = null;
    result = str ?? "default";
    Console.WriteLine(result);
  }
}

C# Null coalescing Operator Advantages

Double question mark operator has advantages over traditional if check

  • First, Improves Code readability and simplicity
  • Null values are avoided by assigning default values.
  • Number code lines reduced, by not using if conditional statements.
  • It improves performance by right-hand operand expression evaluated based on left side operand.

However, It has Disadvantages Need to learn new syntax and understand it.

  • Confusing developers at first