Home All Groups Group Topic Archive Search About

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

Author
27 Feb 2006 9:58 PM
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.

Author
27 Feb 2006 10:06 PM
Herfried K. Wagner [MVP]
"parez" <psaw***@gmail.com> schrieb:
> 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.

--
M S   Herfried K. Wagner
M V P  <URL:http://dotnet.mvps.org/>
V B   <URL:http://classicvb.org/petition/>
Author
27 Feb 2006 10:27 PM
parez
doh!.

Thanks
Author
27 Feb 2006 10:32 PM
parez
I thought it was more like a  ?: operator.. I forgot it was  a
function..
Thanks again
Author
28 Feb 2006 7:33 AM
Cor Ligthert [MVP]
Parez,

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

Cor
Author
28 Feb 2006 1:22 PM
Jay B. Harlow [MVP - Outlook]
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


Show quoteHide quote
"parez" <psaw***@gmail.com> wrote in message
news:1141079568.816497.182130@e56g2000cwe.googlegroups.com...
|I thought it was more like a  ?: operator.. I forgot it was  a
| function..
| Thanks again
|
Author
27 Feb 2006 10:07 PM
parez
I meant it returns str. but it also tries to evaluate the true part
Author
28 Feb 2006 12:09 AM
Dennis
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.
--
Dennis in Houston


Show quoteHide quote
"parez" wrote:

> I meant it returns str. but it also tries to evaluate the true part
>
>