ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Replace if statement with null-propagating code

Last modified: 08 April 2024

Checking for null is probably what you do quite often, for example, to prevent a null reference exception when invoking properties. Using if-statements for numerous null checking makes code cumbersome and lengthy. Starting from version 6.0, C# supports a shorter notation, the null conditional operator. It allows checking one or more expressions for null in a call chain, which is called null propagation. Such a notation can be written in a single line whereas a number of if-else statements typically occupy many lines.

In the example below, the use of the null conditional operator with member access ?. saves you four lines of code: