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
- Nullable Value Types
- Null-Conditional Operator
- Null-Coalescing Operators
- Guarding Against Nulls