ReSharper 2024.1 Help

Code Inspection: Invert 'if' statement to reduce nesting

Category

Language Usage Opportunities

ID

InvertIf

EditorConfig

resharper_invert_if_highlighting

Default severity

Hint

Language

C#

Requires SWA

No

Consider the following code snippet:

void PrintName(Person p) { if (p != null) { if (p.Name != null) { Console.WriteLine(p.Name); } } }

As you can see, the if blocks encompass the whole body of the method. This presents an opportunity to make code more readable by getting rid of the nested scope as follows:

void PrintName(Person p) { if (p == null) return if (p.Name == null) return; Console.WriteLine(p.Name); }
Last modified: 15 April 2024