#215 – Using the Null-Coalescing (??) Operator with Custom Nullable Types

In addition to the built-in nullable types, you can also use the null-coalescing operator on custom nullable types using Nullable<T>.

Here’s an example:

            Nullable<Mood> myMood1 = null;
            Nullable<Mood> myMood2 = Mood.Petulant;

            Mood mood3 = myMood1 ?? Mood.Happy;   // result = Happy
            Mood mood4 = myMood2 ?? Mood.Happy;   // result = Petulant

#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;