The C# Null-Coalescing operator or the ?? operator is a binary operator that returns the left-hand operand if it is not null; otherwise it returns the right operand. It can be used with both nullable and reference types.
Here’s a simple example of using the Null-Coalescing operator
int? i = null;Here are some additional ways of using the Null-Coalescing operator in your code.
int j = i ?? 2;
// here the resultant value of j is 2
returns the first non-null value in this long expression. This expression returns “No Address” if homeAddress1, homeAddress2 and officeAddress are Null.
string address = homeAddress1 ?? homeAddress2 ?? officeAddress
?? "No Address";
While converting a Nullable Type to Non-Nullable type, we do an explicit cast to avoid assigning null values to a non-nullable type, as shown below:
int? a = NullType(); // returns nullable intinstead you can avoid the explicit cast using a null-coalescing operator and write:
int b = (int)a;
int? a = NullType();
int b = a ?? 0;
private IList<Person> person;Typical usage of the null-coalescing operator in a lazy instantiated private variable.
public IList<Person> PersonList
return person ?? (person = new List<Person>());
string conn = Connection["TestMachineStr1"]