0Pricing
C# Academy · Lesson

Null-Coalescing Operators

Use ?? and ??= to provide fallbacks.

The ?? Operator

The null-coalescing operator ?? returns its left operand if it is not null, otherwise the right operand. It is a compact fallback.

using System;

class Program {
    static void Main() {
        int? maybe = null;
        int value = maybe ?? -1;
        Console.WriteLine(value);
    }
}

?? Picks the First Non-Null

If the left side has a value, that value wins and the right side is ignored.

using System;

class Program {
    static void Main() {
        int? a = 7;
        Console.WriteLine(a ?? 0);
    }
}

All lessons in this course

  1. Introducing Nullable Value Types
  2. HasValue and Value Properties
  3. Null-Coalescing Operators
  4. Nullable in Calculations
← Back to C# Academy