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)
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).