mdk.fr/content/blog/the-operator-aka-null-coale...

36 lines
1.2 KiB
Markdown

---
Title: 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 :
:::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:
:::csharp
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 :
:::cpp
string pageTitle = getTitle() ?: "Default Title";
You can get the same behaviour in javascript using the "||" operator :
:::javascript
pageTitle = getTitle() || "Default Title";
You can read more about this operator
[here](http://en.wikipedia.org/wiki/Coalescing_Operator) and
[here](http://en.wikipedia.org/wiki/%3F:)