← Back to C# Course | Chapter 3: Operators | Lesson 6 of 6

Null Coalescing (??)

The double question mark gives you a backup value when something is empty, like 'use my lunchbox, or if I forgot it, buy lunch'. It supplies a default whenever the first thing is null.

In this page:

  1. Null Coalescing (??)
Syntax
csharp
type result = value ?? fallback;   // fallback used when value is null
variable ??= fallback;              // assign only if variable is null

Null Coalescing (??)

The ?? operator returns its left operand if it isn't null, otherwise it returns the right operand — a compact way to supply defaults.

??= goes further, assigning the right side only if the variable is currently null. Both operators exist specifically to reduce verbose null-checking if statements.

Note: x ??= defaultValue; is shorthand for if (x == null) x = defaultValue;.

Example: Null Coalescing (??)

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        string name = null;
        string displayName = name ?? "Guest";

        Console.WriteLine(displayName);

        string city = null;
        city ??= "Unknown";
        Console.WriteLine(city);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using ?? on a value type that cannot be null, which is a compile error.
  2. Confusing ?? (default when null) with ?: (conditional on a bool).
  3. Expecting ?? to treat an empty string as null, when it only checks for null.
Chapter Summary
  • Arithmetic, comparison, and logical operators build expressions.
  • Bitwise operators work on the bits of values.
  • The ternary operator and null coalescing (??) provide short ways to choose values.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.