Skip to content

C# Feature – Null-conditional ?.

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.

C# 6 (2015)

var length = (s != null) ? s.Length : (int?)null;
var length = s?.Length; // int? when s is string?
Person? p = GetPersonOrNull();
Console.WriteLine(p?.Address?.City ?? "Unknown");
  • Mind the nullable type of the result; ?. usually lifts to a nullable type.
  • Combine with ?? for fallbacks.
  • Works well with nullable reference types (C# 8).