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.

string name = null;
string greeting = "Hello, " + (name ?? "Dear");
Console.WriteLine(greeting);

Output:

Hello, Dear

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

string name = null;
string greeting = "Hello, " + (name != null ? name : "Dear");
Console.WriteLine(greeting);

Or

string name = null;
string greeting = "Hello, ";

if (name != null)
  greeting += name;
else
  greeting += "Dear";

Console.WriteLine(greeting);

 

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.

public class User
{
    private readonly string _nickname;

    private readonly string _name;

    private readonly string _lastName;

    public User(string nickName = null,string name = null, string lastname = null)
    {
        _nickname = nickName;
        _name = name;
        _lastName = lastname;
    }

    public string NickName
    {
        get { return _nickname ?? _name ?? _lastName ?? $"guest{new Random().Next()}"; } 
    }
}
static void Main(string[] args)
{
    User user = new User();
    Console.WriteLine(user.NickName);
}

Output:

guest1679841122

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.

string name = "";
string greeting = "Hello, " + (name ?? "Dear");
Console.WriteLine(greeting);

Output:

Hello,