The null-coalescing operator (??) returns the first NON-NULL value from a chain. This operator provide a value for a nullable type when the value is null . It returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.

int a = b ?? -1;
The above code explains, a = b, unless b is null, in which case a = -1. is ame as

if(a != null)
    a = b;
else
    a = -1;

Null Coalescing Operator (??) in C#

Available in C# 8.0 and later, the Null Coalescing Operator (??) is a binary operator that simplifies checking for null values. When you work with nullable value types and need to provide a value of an underlying value type, you can use the ?? operator to specify the value to provide in case a nullable type value is null. You are allowed to use ?? operator with value types and reference types.

It's very handy because you can use any number of these in sequence.

string Answer = Option1 ?? Option2 ?? Option3
Above code will give the result of expression Answer if it's non-null, otherwise try Option1, otherwise try Option2, otherwise try Option3.
Prev
Index Page
Next
©Net-informations.com