The Null Coalescing operator has been around since the early days of C#. Yet it still remains unused by most developers. I'm guessing this is because they are unaware of it, rather than deliberately rejecting it.
The operator is simply a double question mark ("??"). Some people refer to it as the "Elvis Operator" because, if you squint your eyes just right, the curvy parts of each question mark resemble the waves of singer Elvis Presley's famous pompadour-style hair while the dots resemble his eyes.
The operator takes 2 arguments and returns a single value. If the first argument is not null, the null coalescing operator returns that argument; otherwise, it returns the second argument.
This is clarified by the following 2 examples
Of course, the code snippet
String f = d ?? e;
is identical to the following:
The arguments must be nullable and the examples above work because "string" is nullable by default. You may need to use the nullable version of other data types as in the example below that features integers.
You can even use this operator with custom classes and objects, as in the following example.
So why bother using the null coalescing operator? Why not continue to use the longer "if/else" version if the results are the same. There are a couple reasons to use the null coalescing operator: Converting Nullable properties to Non-Nullable properties and Ease of Reading.
Converting to Non-Nullable Properties
The Null Coalescing operator is useful for converting a nullable property into a non-nullable property.
For example, the following example, returns "N/A" for the FavoriteColor property if none is assigned. This assures that FavoriteColor will never return Null.
Ease of reading
The single line of a code allowed by the Null coalescing operator tends to be much more terse and more clear than the multiple lines of an IF/ELSE construct. This is particularly true if you have a lot of similar checks in a row. Given the following examples, it is much easier to read the first than the second. Once you are comfortable with the syntax, it is easy to see what the code is doing. Even though you are almost certainly familiar with the syntax of an "if" construct, you still must pause to step through the code and think about what the second example is doing.
Some will argue that the Null Coalescing operator is more difficult to read because so many are unfamiliar with it. This seems a weak argument to me, given how long it has been in the language and how useful it is. As a developer, we owe it to ourselves to become familiar with the core structures of our language of choice and this includes the operators.
Make your code more concise and readable by using the Null Coalescing operator.