Null Coalescing Operator or ?? in c#

0
515
??

Null Coalescing Operator is the ?? operator

This operator has been added to C# since version 2.0,  and it’s one of the C# syntactic sugars that sometimes is more useful than you expect. Basically, this operator works like a Ternary Operator  for checking a Null value.   

ex:   In this scenario, if the name variable is null then  greeting  variable is going to be "Hello, Dear" , and if we assign a value to the name  variable, it will not be null and instead of "Dear"  the name will be concatenated with the "Hello, " string.

This code can be written in two other ways, one using Ternary Operator and the other using regular if statement.

Or

As you see, Null Coalescing operator is shorter and more readable code in compare to the other two options. This operator can be used for either reference types or nullable value types, like int? bool? float? and etc.

Chaining Null Coalescing Operator

We can also chain the ?? operator when we have another nullable type, which is going to be returned in case the first variable is null :  var z = x ?? y ?? "N/A"

ex: The following User class has a Nickname property, but if the user does not have a nickname, it is going to return the name, and if the name is not available it will return the last name, and finally if none of them are available it will return a random nickname for the user.

Null Coalescing Operator is only a Null value checker an empty string is not null, so if the left variable is an empty string, it still will return that variable.

 

 

SHARE
Next articleLINQ Aggregate Function