Skip to main content

Flatten Conditional

  • 2 minutes to read

#Purpose

This refactoring helps you simplify conditional clauses and increase code readability in the following cases:

  • When nested conditionals can be replaced with a guard clause.
  • When a part of a conditional expression is redundant and can be removed.
  • When a conditional clause can be replaced with a test expression. For example, when a boolean value is assigned or returned inside an if block.

#Availability

Available when the caret is in an if statement and the surrounding code can be simplified.

#Usage

  1. Place the caret in a suitable if statement.

    public bool MyBinaryOperator(bool a, bool b)
    {
        if (a && !b)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select Flatten Conditional from the menu and press Enter.

    menu-item

After execution, this refactoring simplifies the conditional clauses.

public bool MyBinaryOperator(bool a, bool b)
{
    return a && !b;
}
See Also