Skip to main content

Compress to Ternary Expression

Converts an if/else conditional into an expression that uses a ternary operator (“? :” operator in C# and C++, IIf operator in Visual Basic).

#Purpose

This refactoring can help you avoid code duplication. It can compress two similar code lines within if and else blocks into a single-line expression, eliminating the need to make future changes in two places.

#Availability

Available from the context menus or via shortcuts:

  • when the caret is on a if statement that has the corresponding else block. Both if and else blocks should contain one statement. These statements should be similar assignments or method calls with different arguments.

#Notes

#Example

if (a)
    b = 10;
else
    b = 20;
If a Then
    b = 10
Else
    b = 20
End If

Result:

b = a ? 10 : 20;
b = If(a, 10, 20)

#Animation

CSharpCompressToTernaryExpression

See Also