Back to Devexpress

Compress to/Expand Ternary Expression

coderushforroslyn-115431-refactoring-assistance-compress-to-expand-ternary-expression.md

latest2.1 KB
Original Source

Compress to/Expand Ternary Expression

  • Aug 19, 2021
  • 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.

  2. Press 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.

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

    return ref (arr1 != null ? ref arr1[0] : ref arr2[0]);
}
vb
b = If(a, 10, 20)

See Also

Compress to/Expand Null Coalescing Operation

Use Expression Body

Collapse/Expand Method

Convert to/Decompose Initializer

ForEach to Linq