JetBrains Rider 2022.2 Help

Code Inspection: Invert 'if' statement to reduce nesting

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: 08 March 2021