Question Mark in C#

Minahil Noor Dec 11, 2023
Question Mark in C#

This article will introduce question mark and dot operator meaning in C#.

Use the ?. Operator as a Null Conditional Operator in C#

We use the ?. operator as a null conditional operator in C#. The dot after the question mark shows the member access. The ?. null-conditional operator applies a member access operation to its operand only if that operand evaluates to non-null; otherwise, it returns null. The correct syntax to use this symbol is as follows.

A?.B

In the above example, B is not evaluated if A evaluates to null.

The program below shows how we can use the null conditional operator.

using System;
public class Program {
  public static void Main() {
    int[] array = new int[5];
    Console.WriteLine(array.GetType());
    int[] array1 = null;
    Console.WriteLine(array1?.GetType());
  }
}

Output:

System.Int32[]

In the above code, we can see that the GetType() function has returned the type of array. But it has not returned the type of array1. It is because array1 is null and we have used the null conditional operator.