• Saves Valuable Time
  • Trusted Accuracy since 2004
  • 15-Day Money-Back Guarantee

VB Equivalent to the C# Ternary Operator

In VB9, the equivalent of the C# ternary operator is the new If operator.

Prior to VB9, the equivalent of the C# ternary operator is the If/Else block.  Although the VB IIf function can be used in a similar way to the conditional ternary operator (?) of C#, it is not equivalent.  VB's IIf function needs to evaluate all arguments since it is a method (method calls always evaluate all arguments), but the ternary operator is able to bypass some evaluations (using short-circuit logic in a similar way to the logical operators && and ||).

For example, the following C# code:
Target = Condition ? ResultOne : ResultTwo;

Has the following VB equivalent, prior to VB9:
If Condition Then
    Target = ResultOne
    Target = ResultTwo
End If

The following VB code is not functionally equivalent since both ResultOne and ResultTwo will be evaluated:
Target = IIf(Condition, ResultOne, ResultTwo)

Use Instant VB to convert from C# to VB.NET.     

Additional resource: VB.NET and C# Equivalents

Copyright © 2004 – 2021 Tangible Software Solutions, Inc.