The ?? operator aka the Null Coalescing Operator

November 23rd, 2008 by valerian

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

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

Download this code: bad_situation.cs

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";

Download this code: solution.cs

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";

Download this code: solution.cpp

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

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

Download this code: solution.js

You can read more about this operator here and here

Leave a Reply