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

Null Coalescing (??)

In this page:

  1. Null Coalescing (??)

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);
    }
}
🔒

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.