WARNING: VB code!
Here is a very popular problem that many VB developers fail to see. Furthermore, it is hard to find once in the code. Can you spot it?
imports Microsoft.VisualBasic imports System public module MyModule sub Main dim a as integer = 0 dim b as integer = CInt(iif(a=0, 100, SomeCalc(a))) end sub private function SomeCalc(a as integer) as integer if a = 0 then throw new ArgumentNullException("a") else return CInt(100 / a) end if end function end module
oh my lovely vb π
iff runs always the true and the false part of expression?
And the grand prize (fame) goes to Giuseppe :-), indeed, IIF *always* runs both parts reagardless of condition.
This is one of the nastiest bug in VB since many VBers fails to realize this fact. And later on it is hard to spot…
i have another nasty “bug” in VB.NET
Dim test As Integer
test = Nothing
ha ??? int32 is a reference type? nice! who needs Nullable Types? lol
the vb compiler translate this line of code to test = 0
i don’t understand why the vb.net compiler allows that.
Both parts!!??? Whoa… π So it doesn’t work at all?
Giuseppe: I don’t understand the rationale either. Seems like a bug to me. “Option Strict On” should issue an error but it doesn’t. And yes, the implicit conversions are another menace to developers.
Frans: Well, you could look it from this perspective: since VB runs two statements and C# runs only one (using ternary operator ?: ) it makes VB a more powerfull language π
SomeCalc(a) has to be calculated before is passed to Iif function (or am I wrong?) – so this is normal operation.
You are correct. But trust me, many VBers think it works like ?: operator.