Back to Devexpress

Reverse Conditional

coderushforroslyn-115575-refactoring-assistance-reverse-conditional.md

latest2.1 KB
Original Source

Reverse Conditional

  • Aug 03, 2020
  • 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

  1. Place the caret on the if keyword.

  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.

  3. Select Reverse Conditional from the menu.

After execution, the Refactoring reverses the checked condition and swaps the if and else blocks.

csharp
if (!found) {
    Console.WriteLine("No records found.");
    return;
}
else
    Console.WriteLine($"Found record at the position {i}");
vb
If Not found Then
    Console.WriteLine("No records found.")
    Return
Else
    Console.WriteLine($"Found record at the position {i}")
End If

In the example above, the else block is redundant. You can move its contents out of the conditional as shown below.

csharp
if (!found) {
    Console.WriteLine("No records found.");
    return;
}
Console.WriteLine($"Found record at the position {i}");
vb
If Not found Then
    Console.WriteLine("No records found.")
    Return
End If
Console.WriteLine($"Found record at the position {i}")

See Also

Reverse Boolean

Flatten Conditional

Conditional to Switch/Switch to Conditional

Combine/Split Conditional(s)