Description
Issue moved from MicrosoftDocs/feedback#2922
- Please respond to @slepmog.
From @slepmog on Monday, July 6, 2020 8:58:28 PM
Describe the bug
The VB.NET IIf
function documentation: https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.interaction.iif?view=netcore-3.1
In the Remarks section, it claims that
The
IIf
function provides a counterpart for the ternary Conditional Operator: ? : in Visual C++.
This is very incorrect, because the main feature of the ternary operator ? :
is that it short-circuits, only evaluating one of its branches and not both.
VB.NET does have a ternary operator of its own, it is called If()
operator. That is indeed a counterpart for the ternary Conditional Operator in C++.
The IIf
function, on contrary, evaluates both its arguments at all times. It had this behaviour in VBA and in VB6, and it still has it in VB.NET, which can be easily verified:
Sub Main()
Dim result = IIf(Rnd() > 0.5, SideEffect1(), SideEffect2())
End Sub
Private Function SideEffect1() As Integer
Console.WriteLine("Side effect 1 caused")
Return 1
End Function
Private Function SideEffect2() As Integer
Console.WriteLine("Side effect 2 caused")
Return 2
End Function
Which outputs:
Side effect 1 caused
Side effect 2 caused
as expected.
The current documentation makes it sound like there is no difference between the If()
operator and the IIf()
function.
This is a very important omission that will lead to incorrect expectations and wrong code.
Expected behavior
Please fix the documentation to reflect the fact that IIf
does not short-circuit, is not therefore a counterpart for the ternary operator, and evaluates its arguments at all times, leading to potentially unwanted side effects. Respective wording can be taken from the VBA documentation Remarks section where it is correct.