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";
pageTitle = getTitle() || "Default Title";