#211 – Using the Null-Coalescing (??) Operator

In C#, the ?? operator, know as the null-coalescing operator, is often used with nullable types.

The ?? operator is used in an expression of the form:

            operand ?? nullval

This expression evaluates to:

  • operand, if operand is non-null
  • nullval, if operand is null

The operand is a variable and the nullval is a variable or constant of the same type as the variable.

The ?? operator is generally used where you have a nullable type and you want to assign its value to a non-nullable type.  Since the nullable type can have the value of null, you need to specify what non-null value to assign in that case.

Here’s an example:

            uint? age = null;   // Nullable age -- might not have a value

            // Later: assign to a non-nullable uint.
            //   Store the age (if non-null)
            //   Store 0  (if null)
            uint ageStore = age ?? 0;
Advertisements