0Pricing
C# Academy · Lesson

Null-Coalescing Operators

?? and ??= defaults.

Supplying a Fallback

Often you want to use a value if it exists, or a default if it is null. The null-coalescing operator ?? does exactly this.

a ?? b means: use a if it is not null, otherwise use b.

string input = null;
string name = input ?? "Guest";
System.Console.WriteLine(name);

How ?? Evaluates

The left side is evaluated first. If it is non-null, the right side is never evaluated at all.

This short-circuiting means an expensive fallback only runs when actually needed.

string cached = "data";
string value = cached ?? Compute();
System.Console.WriteLine(value);
// Compute() is never called here

All lessons in this course

  1. Nullable Value Types
  2. Null-Conditional Operator
  3. Null-Coalescing Operators
  4. Guarding Against Nulls
← Back to C# Academy