The ?? operator aka the Null Coalescing Operator

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

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

This entry was posted in Code and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>