Compress to/Expand Ternary Expression


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. Ternary expressions make your code much more compact.


  • The Compress to Ternary Expression Refactoring is available when the caret is on an if statement that has the corresponding else block. Both 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.


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


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

    if (a)
        b = 10;
        b = 20;
  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.

b = a ? 10 : 20;

See Also