VB.Net Tip: IIF is a function, not a language feature
secretGeek .:dot Nuts about dot Net:.
home .: about .: sign up .: sitemap .: secretGeek RSS

VB.Net Tip: IIF is a function, not a language feature

I think i've found a nice way to demonstrate this age old gotcha in VB.

What result do you expect from this line of VB code?

IIf(True, MsgBox("hello"), MsgBox("goodbye"))

(continues...)

Do you expect only the first message box to show up?

You might think it would just execute the:

MsgBox("hello")

But you'd be as wrong as a fez with a brim.

BOTH message boxes will come up, one after the other. Try it and see.

Is this a bug? Is this insane? Is this dangerous?

No, no and yes occasionally. The thing is that IIF is just a built in function. And when you try to send expressions to it, they get evaluated before the function sees them. The same happens any time you send expressions to any function.

So it's not a bug, and it's also unlikely to change in any version of VB, or any future version of the IIF function. So it's worth taking the time to remember it, understand it and work with it.

Now when is this likely to pose a problem?

To avoid a divide-by-zero error, many a coder has tried this:

IIf(divisor=0, c, a / divisor)

And they will of course still get a "Divide By Zero" error, if the divisor equals zero.

Again, that's because IIF is just a function. And like all functions in vb, it doesn't accept expressions as parameters. So the expressions must be evaluated before they are passed to the IIF function. Hence the error.

The longer syntax, using full if statements, will work as desired:

        If divisor = 0 Then

            Return c

        Else

            Return a / divisor

        End If

And that's pretty much the best way to skin this little kitten.

(thanks to derek for reminding me to post about this)


One little footnote, is that in Excel, if you type:

        IF (TRUE,TRUE, 5/0)

...you won't get an error message -- because some sort of shortcutting is happening, and the false code path isn't executed.

So, to get a "#DIV/0!" error message, you'd need to get that particular trouser leg of the if statement to fire, like so:

        IF (FALSE,TRUE, 5/0)





'Locutus of Borg' on Tue, 09 May 2006 08:16:48 GMT, sez:

This is actually one of the few real differences between C# and VB.NET apart from syntax.
In C#
a = (c==0) ? 0 : (b/c);
works like a charm.
As illustrated by Leon, VB.NET's IIf is realy a function whose parameters are first evaluated before being passed to the function.
It's strange that while VB.NET is breaking backward compatibility in all sorts of places, IIf somehow escaped it's fate.



'John Meyer' on Tue, 09 May 2006 12:07:02 GMT, sez:

IIF is specific to VB, not part of the CLR. Therefore by definition it is a language feature. And that the VB compiler does not short-circuit this language specific construct is a compiler bug. Why do I use C# instead of VB? Simple! VB's compiler is broken! Full of dangerous bugs that are written off as "Features".

Another example, the statment...
If (obj <> Nothing Or obj.Property = "something")
IS guaranteed to not throw a null reference exception... unless the compiler is broken



'lb' on Tue, 09 May 2006 20:25:39 GMT, sez:

>"Full of dangerous bugs"

that's a bit harsh isn't it?

I'm sure they've left enough room for more bugs in later versions.

maybe in vb 3 it was a genuine bug, but by this stage in the game it's a genuine feature. it didn't get in there by accident, it's in there on purpose now.

Hence VB.net has the shortcutting conditions 'orelse' and also 'andalso'

If (obj <> Nothing OrElse obj.Property = "something")

the fact that 'OrElse' and 'AndAlso' are inelegant at first is not a big problem.

go easy on the language cousin.



'Farmer Jeb' on Wed, 10 May 2006 00:46:57 GMT, sez:

Now hang on a cotton-picking minute... Shortcutting with OrElse means it only bothers to execute the dangerous second expression, obj.Property = "Something", if the safe first expression, obj <> Nothing, is False. If this expression is False, obj is not not Nothing ie. obj IS Nothing. The dangerous second expression is guaranteed to be executed if and only if the object is nothing. This code is asking to crash!!
(Change <> to =.)



'lb' on Wed, 10 May 2006 00:52:24 GMT, sez:

Well if we're picky...

'nothing' comparisons use 'is' not 'equals',

So:

if obj is Nothing OrElse obj.Property = "something"

or:

if Not obj is Nothing AndAlso obj.Property = "something"....

yeh.



'rob' on Thu, 11 May 2006 22:33:09 GMT, sez:

how do you format your code into html for blogging?



'Atli' on Sun, 14 May 2006 20:08:22 GMT, sez:

Let's not forget the new IsNot operator:

if obj IsNot Nothing AndAlso obj.Property = "something"....

And BTW, IIF is not a language feature but a function within the Microsoft.VisualBasic namespace (within the Interaction module). So C# programmers can use it, although I see no reason for the to wanting it.

However, IIF function could be better implemented by using generics (to avoid the typecasting).



'steve flit' on Tue, 30 May 2006 21:05:34 GMT, sez:

    Public Function IIf(Of T)(ByVal expression As Boolean, _

                ByVal truePart As T, ByVal falsePart As T) As T

        If expression Then

            Return truePart

        Else

            Return falsePart

        End If

    End Function



'lb' on Tue, 30 May 2006 21:07:18 GMT, sez:

thanks Steve!



'ffdf' on Tue, 07 Nov 2006 07:50:48 GMT, sez:

fdgfdff



'Hans Peter' on Tue, 16 Jan 2007 13:22:54 GMT, sez:

As it is now IIf is definately not more than a function and should not be treated as a special statement type in the VB compiler, if they do that, then they are more stupid than I thought. And how could then not notice such a bug if there was one?

I agree, VB is absolute crap in my opinion. Far to "chatty" as well. In my opinion C# is much easier to overview, and less to write.



'Tyler' on Mon, 26 Mar 2007 15:13:26 GMT, sez:

And to think i was looking for a feasible solution that would allow me to do ternary operators like I can use in PHP but for VB



'C# is for the birds' on Tue, 27 Mar 2007 19:26:08 GMT, sez:

your right HANS I do greatly appreciate having to place arbitrary ; at the end of every single statement just so I can occationally be sloppy and place multiple statements on a single line or to redomly break my line to others.

Not to mention how much fun it is to track those wonderful {} just to figure out where to end every if, when, function or class because they all look exactly the same.


I am very fluent in both languages and VB developement and support time is half of the C# time. Get to know a language before you cut it down.

Tell me how
for x as integer = 0 to 10
'multiple lines of code
next

is more chatty then

for (x=0; x<11; j++)
{


} // end for x
if you are sloppy you could omit //





'FM' on Tue, 29 May 2007 20:28:33 GMT, sez:

lol on the j++ in the previous posters C code. :o



'Anonymous Jackass' on Mon, 04 Jun 2007 09:27:22 GMT, sez:

Don't worry, he's fluent in both languages.



'seanboy' on Fri, 06 Jul 2007 12:04:24 GMT, sez:

Mmmm. VB.Net for life!

I don't like using inline If's, If I need to do something inline I write a function for it. then again I am just some punk kid so who knows..



'lb' on Fri, 06 Jul 2007 12:09:22 GMT, sez:

@seanboy
>I am just some punk kid so who knows

hey -- this world was built by punk kids like you, so don't ever doubt yourself!

write that function! show the world, man!!

lb



'AdmSteck' on Mon, 01 Oct 2007 13:39:16 GMT, sez:

Why does every post about the 'features' or 'bugs' of VB always become an argument about whether C# is better? Any why are C# coders even reading a forum post about VB unless they have the intent of spouting how 'insert language here' is better than VB? Use what you like and leave the rest of us alone when we choose to use what we like.



'Robdog' on Tue, 06 Nov 2007 19:18:35 GMT, sez:

EVERY language has small advantages and disadvantages. That's why they were created and why most of us don't work with assembler anymore. You know you've rewritten good C# code in VB... and the C# guys are here looking for the same.
Jes chill and learn from each other.



'Ron' on Thu, 13 Mar 2008 22:10:55 GMT, sez:

VB fanatics take a chill...short-circuited IIf would be extremely handy...just a matter of time before this or some better mechanism shows up in VB...until then, I'll pine for it...



'Mark' on Wed, 23 Apr 2008 17:20:21 GMT, sez:

Great job on the article. It was especially handy that Googling "iif vb.net" returned this article first :)

It is good to learn that IIf is not a true ternary operator.

To other's points about why C# developers would be reading this, programmers should try to be capable in any language. So when a C# developer has to maintain, modify, or write new VB.NET code, they sometimes have to research the nuances of it. For example, the differences between And and AndAlso, when you are used to the logical constraint of "&&".



'Alberto' on Thu, 04 Sep 2008 07:05:48 GMT, sez:

BTW, VB9 introduces a new and syntactically simplified form of the ternary operator called If (note the loss of the extra "I") that prevents the unwanted behavior by evaluating only the appropriate expression—the other expression is never evaluated.
so, the statements

If(divisor=0, c, a / divisor)

or (to replace null strings with string.empty)

str = If(str, String.Empty)

will work fine

The new ternary operator (If version) is available even if you target the 2.0 framework.



'sreelal' on Fri, 23 Jan 2009 14:20:59 GMT, sez:

how to comment the multiple statements in VB



'Hater of VB' on Tue, 24 Feb 2009 16:38:56 GMT, sez:

Anyone who cuts down C# and prefers VB obviously is not a good developer. It's all you VB guys that create havoc for systems. Wait, you don't know what systems development is! VB guys write slop in my experiences. And I am fluent in both, but VB should die!



'lb' on Tue, 24 Feb 2009 18:04:26 GMT, sez:

@Hater
don't be a hater, Hater.



'js' on Wed, 11 Mar 2009 13:40:38 GMT, sez:

@hater...
c# developers can write slop too you know. Mind you, if you were fluent in all these languages, why are you looking up "iif" ?

(p.s. I know Pascal too, and spent 4 months in Cobol - do any of these help?)



'Al' on Mon, 13 Apr 2009 03:57:30 GMT, sez:

http://msdn.microsoft.com/en-us/library/bb513985.aspx



'Mohan' on Mon, 27 Apr 2009 01:37:44 GMT, sez:

Thanks "steve flit" for this:

Public Function IIf(Of T)(ByVal expression As Boolean, _
ByVal truePart As T, ByVal falsePart As T) As T
If expression Then
Return truePart
Else
Return falsePart
End If
End Function




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. But the right to delete any post for any reason is reserved. Don't make me do it. Comments may be republished, emailed to your loved ones or printed and used as toilet paper. Who reads this legal bit anyhow?

TimeSnapper is a life analysis system that stores and plays-back your computer use. It makes timesheet recording a breeze, helps you recover lost work and shows you how to sharpen your act.

TimeSnapper won last year's Developer Competition at Larkware.com, and is used by over 10,000 people.

Articles

Is the remote control a thing of the past? Is the remote control a thing of the past?
The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7. The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7.
Astounding Hyperlinked Noticeboard Astounding Hyperlinked Noticeboard
Three Questions About Each Bug You Find Three Questions About Each Bug You Find
Recursing over the Pareto Principle... Recursing over the Pareto Principle...
Sometimes, The Better You Program, The Worse You Communicate. Sometimes, The Better You Program, The Worse You Communicate.

Archives .: secretGeek :: Complete Archives
TimeSnapper -- Automated Screenshot Journal TimeSnapper.com    
Version 3.3: true productivity boost

Next Action NextAction
Managing the top of your mind

World's Simplest Code Generator (html edition) World's Simplest Code Generator
25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker


[powered by Google] 


How to be depressed How to be depressed
You are not inadequate.



Recommended Reading

The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Reginald Braithwaite
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink
Joel Spolsky
Des Traynor

Aggregated Links

programming.reddit.com
dzone
dot net kicks

Human Link Machines

interesting finds
a continuous learner's weblog
arjan's world
n links today
new and notable
morning coffee
learning .net
weekly link post
(my del.icio.us account)

LinkedIn profile
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2003 .: privacy

home .: about .: sign up .: sitemap .: RSS .: © Leon Bambrick 2003 .: privacy