C# Feature – Null-conditional ?.
Overview
Section titled “Overview”The null-conditional operator ?.
lets you safely access members when the receiver may be null; if the receiver is null, the entire expression evaluates to null.
Introduced In
Section titled “Introduced In”C# 6 (2015)
Before
Section titled “Before”var length = (s != null) ? s.Length : (int?)null;
var length = s?.Length; // int? when s is string?
Annotated Example
Section titled “Annotated Example”Person? p = GetPersonOrNull();Console.WriteLine(p?.Address?.City ?? "Unknown");
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Mind the nullable type of the result;
?.
usually lifts to a nullable type. - Combine with
??
for fallbacks.
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”- Works well with nullable reference types (C# 8).