Chaining Null-Coalescing Operator in C#

What is Null-Coalescing Operator?

Null-Coalescing operator is double question mark (??). It returns the left hand operand if not null, else returns the right hand operand.


Consider following example, where null-coalescing operator is not used. We have two variables one is nullable int and the other is int. The index is checked for null and we have a valid if else statement.


The above piece of code could be re-written into something below using the null-coalescing operator. As mentioned earlier the index is checked for null if not null, the value is returned else the -1 value is returned.


Chaining Null-Coalescing Operator

Chaining is very simple; here we would add the values to be checked for null one after another. In the following example, previousIndex is another nullable variable, which is checked if index is null. And if previousIndex is null -1 is returned.


Let’s add some value to previousIndex to check it properly.


Now we have kept two breakpoints one before assigning the previousIndex value and one after the null-coalescing chain operator statement. As you see in the following, selectedIndes is -1 as index and previousIndex are null.


But after the value is assigned as 3 to previousIndex, and the statement breaks there where it finds not-null for previousIndex and returns the value 3, which is assigned to selectedIndex.


The following diagram shows that, we could have chaining of Null-Coalescing Operator as follows.


Hope this post was useful.

Thanks for reading. Like Method Of Tried in Facebook.