IIF in vb.net acts weird.. or is it me

  • Thread starter Thread starter parez
  • Start date Start date
P

parez

Hi all,

why in the world would this fail ( throw an exception)


Dim str As String = ""

MsgBox(IIf(IsNumeric(str), Convert.ToInt32(str).ToString, str))

Why does it try to evaluate the true part when the condition is false.

Or am i missing something here.

Thanks in advance.
 
parez said:
why in the world would this fail ( throw an exception)


Dim str As String = ""

MsgBox(IIf(IsNumeric(str), Convert.ToInt32(str).ToString, str))

Why does it try to evaluate the true part when the condition is false.

Because it's a function.
 
It's similiar to If xxx and yyy then...both are evaluated whereas in If xxx
andalso yyy then... only the first xxx is evaluated if it's false...yyy is
only evaluated if xxx is true.

If you pass parameters to a function, all are evaluated to their final value.
 
Parez,

Not only however mainly because its behaviour is mostly advices to avoid the
IIF in VBNet.

Cor
 
Parez,
As Cor suggests a number of developers discourage its use, as it does
evaluate both of its parameters, which may have undesired side effects as
you found out. Plus it is not Option Strict On friendly, as it accepts
Object as its parameters & returns an Object. Accepting & returning Object
means that it will box value parameters, which is a slight performance hit &
causes extra pressure on the GC. Returning object means you need to cast to
the specific type, leading to "awkward" code.

In places where it does make sense to use the IIf function, I normally use
my Generic IIf function. Being Generic removes the "boxing penalty" and the
"awkward" code factor. However its still a function ;-)

http://www.tsbradley.net/Cookbook/Generics/genericIIf.aspx



--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


|I thought it was more like a ?: operator.. I forgot it was a
| function..
| Thanks again
|
 
Back
Top