0Pricing
C# Academy · Lesson

Null-Conditional Operator

Safe access with ?.

The Problem of Null Chains

Accessing a member on a null reference throws a NullReferenceException. This is one of the most common runtime crashes in C#.

When you chain calls like user.Address.City, any link in the chain might be null, and the old fix was a tower of if checks.

Meet ?.

The null-conditional operator ?. short-circuits the whole expression. If the left side is null, the result is null instead of an exception.

It reads as: "access this member, but only if the object is not null."

string name = null;
int? length = name?.Length;
System.Console.WriteLine(length == null);

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