Reverse Conditional
- 2 minutes to read
#Purpose
Used to swap the if and else blocks in a conditional without changing the program behavior. Swapping the if and else blocks can improve the code readability.
You can also use this Refactoring when the else block ends with a return, break or continue jump statement and can be converted to the guard clause with no else block.
#Availability
Available when the caret is on the if keyword.
#Usage
Place the caret on the if keyword.
Note
The blinking cursor shows the caret’s position at which the Refactoring is available.
- Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
- Select Reverse Conditional from the menu.
After execution, the Refactoring reverses the checked condition and swaps the if and else blocks.
if (!found) {
Console.WriteLine("No records found.");
return;
}
else
Console.WriteLine($"Found record at the position {i}");
In the example above, the else block is redundant. You can move its contents out of the conditional as shown below.
if (!found) {
Console.WriteLine("No records found.");
return;
}
Console.WriteLine($"Found record at the position {i}");