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:
|Suboptimal code||After the quick-fix|
| || |
Last modified: 20 August 2018