DevPinoy.org
A Filipino Developers Community
   
A weird VB feature

A friend asked me for help today about a segment of code that was giving him a headache. After looking at the code I immediately told him the problem. Can you spot the problem too without compiling the VB code? Why is it happening?

Module Program

    Sub Main()
        Calculate()
    End Sub

    Private Sub Calculate()
        Dim value1 As Integer = 0

        'Imagine that the value of value1 has been manipulated on this section
        '///--> Insert imaginary code here <---

        Dim value2 As Integer = CInt(IIf(value1 <= 0, 100, CalculateValue(value1)))
    End Sub

    Private Function CalculateValue(ByVal value1 As Integer) As Integer
        If (value1 <= 0) Then
            Throw New ArgumentOutOfRangeException("Parameter cannot be less than 1!")
        Else
            Return CInt(100 / value1)
        End If
    End Function

End Module


Posted 05-25-2007 5:02 PM by keithrull
Filed under: ,

Comments

Jason wrote re: A weird VB feature
on 05-25-2007 10:48 PM

I believe this is because the IIf function evaluates all 3 arguments and does not short-circuit like a true ternary operator. Paul Vick says this is coming to VB in Orcas: www.panopticoncentral.net/.../20433.aspx

keithrull wrote re: A weird VB feature
on 05-26-2007 12:00 AM

Thats right Jason.

Most C# developers who are assigned to VB.NET projects doesn't immediately recognize this issue causing them to loose their hair in the debugging process.

I have known this IIf issue since my early days with VB which is the reason why I was able to recognize the bug in an instant. Thanks for the tip about the fix coming in Orcas ;)

Jon Limjap wrote re: A weird VB feature
on 05-27-2007 8:19 AM

That's right... IIf is, technically, a function, and is not short-circuit-complied unlike the ? ternary operator.

Furthermore, in VB logic, by default it still evaluates all conditions, e.g., If a And b it still evaluates b even if a is already false. You have to use the AndAlso and OrElse syntax. So if it happens that a is a check if an object is null(Nothing) and b is an access to that object, and you used And instead of AndAlso, a runtime error will occur.

Copyright DevPinoy 2005-2008