The null-coalescing operator ??
returns the value of its left-hand operand if it isn’t null
; otherwise, it evaluates the right-hand operand and returns its result.
The ??
operator doesn’t evaluate its right-hand operand if the left-hand operand evaluates to non-null.
int? myValue = null; int result = myValue ?? -1; //result = -1;
Syntax:
p ?? q
Here, p is the left and q is the right operand of ?? operator. The value of p can be nullable type, but the value of q must be non-nullable type. If the value of p is null, then it returns the value of q. Otherwise, it will return the value of p.
Important Points:
- The ?? operator is used to check null values and you can also assign a default value to a variable whose value is null(or nullable type).
- You are not allowed to overload ?? operator.
- It is right-associative.
- In ?? operator, you can use throw expression as a right-hand operand of ?? operator which makes your code more concise.
- You are allowed to use ?? operator with value types and reference types.
The null-coalescing assignment operator ??=
assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null
.
The ??=
operator doesn’t evaluate its right-hand operand if the left-hand operand evaluates to non-null.
int? myValue = null; myValue ??= 0; //myValue = 0;