Home of the AlmostImplementedException

The ?? Operator (null-coalescing – Operator)

The good thing about other peoples code is you learn always something new. Today i came across the ?? operator (a.k.a. null-coalescing). Until now i only know the single questionmark operator (Conditional-Operator), but not two question marks and wondered what it might do.
The answere is quite simple and i can think of many cases where it come in handy.

The two question marks (??) means nothing else then “If the first parameter is not null, then use it. Otherwise use the second one”. Here is a little example:

First, method1() is called and if the result is not null, the variable obj ist set with the value. But if the method returns null, method2 is called and obj will be set with the returned value.
So, the ?? operator is nothing else then a shorter way for this code:

This Code is known as the Conditional-Operator and you can read more about it when you follow the link. There is also an explanation what final code is generated.

The beautiful thing about the ?? operator you can use it as many times as you want in one statement:

This code calles one method other another until a result is not null. If the last value is null, the variable obj will of course be set with null;
Since the method 2 to 4 are only called if the predecessor returned null, this code is not just small but also very fast.

But a word of warning, the code might be harder to read if you overuse the ?? operator.

Share :

, , , , , , ,

Leave a Reply