What??

The Double Question mark in C# — ??

This null-coalescing operator

Daniele Quero, PhD
Published in
3 min readJul 12, 2022

--

It is called null-coalescing operator. Aka double question mark.

Single Question Mark Overview

We are no strangers to the use of the single question mark operator, in almost any programming language:

MyClass myObj = (condition) ? value : alternative;

The condition is evaluated and if it is true a value is returned, otherwise we get the alternative. It’s like:

if(condition)
myObj = value;
else
myObj = alternative;

The null-coalescing operator does a similar trick. It evaluates the value and returns it only if it is non-null. Otherwise, the rightmost operand is evaluated and its result is returned, let’s see:

myObject = value ?? alternative;

If value != null then it will be assigned to the variable, otherwise, we get the other one. It’s like the COALESCE() function in SQL.

Good to know

The right operand is not evaluated if the left one is not null. This allows powerful implementations, like this one:

myObj = value ?? throw new ArgumentNullException(…

--

--

Daniele Quero, PhD
Geek Culture

A professional developer with passion for game developing and skill-growing. A former Nuclear Physics Researcher who changed his life to pursue his dreams