Skip to content
bagley2014 edited this page Nov 12, 2021 · 1 revision

Prefer null-conditional operators over ternaries

The null-conditional operator provides a simpler, clearer way of checking for null before doing a member access.

// Unnecessarily verbose
foo != null ? foo.Bar : null
foo == null ? null : foo.Bar
bat.HasValue ? bat.Value.Bar : null // bat is of type Nullable<T>
!bat.HasValue ? null : bat.Value.Bar

// Preferred
foo?.Bar
bat?.Value.Bar

Null-conditional docs

Clone this wiki locally