ReSharper 2024.3 Help

Code inspection: Replace if statement with null-propagating code

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:

public string GetName(object name) { if (name != null) { return name.ToString(); } return null; }
public string GetName(object name) { return name?.ToString(); }
Last modified: 08 April 2024