Can you spot the problem (VBx/VB.NET)


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

7 replies on “Can you spot the problem (VBx/VB.NET)”

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 compiler allows that.

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 πŸ˜›

Leave a Reply