Skip to main content
A newer version of this page is available. .

Compress to/Expand Ternary Expression

  • 2 minutes to read

Purpose

Converts an if-else conditional into an expression that uses a ternary operator ("? :" operator in C#, inline IIf function in Visual Basic) and vice versa. These refactorings also support ref ternary expressions. Ternary expressions reduce the amount of code.

Availability

  • The Compress to Ternary Expression refactoring is available when the caret is on a if statement that has a corresponding else block. The if and else blocks should contain one statement. These statements should be similar assignments, returns or method calls with different arguments.
  • The Expand Ternary Expression is available when the caret is on an expression containing a ternary operator.

Usage

  1. Place the caret on a compressible if-else expression.

    NOTE

    The blinking cursor shows the caret's position at which the Refactoring is available.

    public ref int GetValue(int[] arr1, int[] arr2) {
    
        if (arr1 != null)
            return ref arr1[0];
        else
            return ref arr2[0];
    }
    
  2. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
  3. Select Compress to Ternary Expression from the menu (Expand Ternary Expression if you are expanding the ternary expression).

After execution, the Refactoring compresses an if-else conditional into an equivalent ternary expression or expands the ternary expression into an equivalent if-else conditional.

public ref int GetValue(int[] arr1, int[] arr2) {

    return ref (arr1 != null ? ref arr1[0] : ref arr2[0]);
}
See Also