Welcome to RightHand's community place Sign in | | Help

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

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
Published 18. oktober 2006 9:16 by Miha Markic
Filed under:

Comments

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

18. oktober 2006 10:05 by Giuseppe
oh my lovely vb ;-) iff runs always the true and the false part of expression?

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

18. oktober 2006 10:11 by Miha Markic

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...

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

18. oktober 2006 10:41 by Giuseppe
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.

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

18. oktober 2006 10:45 by Frans Bouma
Both parts!!??? Whoa... :) So it doesn't work at all?

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

18. oktober 2006 11:05 by Miha Markic

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 :-P

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

18. oktober 2006 17:24 by Matej
SomeCalc(a) has to be calculated before is passed to Iif function (or am I wrong?) - so this is normal operation.

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

18. oktober 2006 18:29 by Miha Markic

You are correct. But trust me, many VBers think it works like ?: operator.

Anonymous comments are disabled