The ?? operator aka the Null Coalescing Operator

Posted on Tue 04 April 2017 in blog

If are familiar to the use of ternary operators, you must have encountered several situations like this one :

:::csharp string pageTitle = getTitle() ? getTitle() : "Default Title";

You would want to call getTitle() only once, but then you wouldn't have a simple one-lined initialization of you variable. Actually there is a simple solution that most langages implements, the null coalescing operator; let's replace the above C# code with this one:

string pageTitle = getTitle() ?? "Default Title";

Now you have the same behaviour, but with only one call to your function. The syntax is simple : possibly_null_value ?? value_if_null the "??" operator is implemented in C# since C# 2.0. You also have it in C and C++ as a GNU extension using the "?:" operator :

string pageTitle = getTitle() ?: "Default Title";

You can get the same behaviour in javascript using the "||" operator :

pageTitle = getTitle() || "Default Title";

You can read more about this operator here and here