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



'rainabba' on Wed, 19 Aug 2009 07:01:00 GMT, sez:

I find it amusing how all the C# fanatics are bagging on VB.Net (in particular 'Hater of VB' saying the VB coders don't know what systems development is) when both languages are really more RAD platforms than anything and any "hardcore" developer is using C++ (be it Windows, Linux, BSD, etc...) anyway.

I've worked with all the platforms and languages I just mentioned and for typical LOB applications, i'll take VB.Net any day for FAST development with minimal lanugage nuances to get in the way (; and {} are a PITA and if you say otherwise, you're not fooling anybody buy maybe yourself).

Yes, it has shortcomings, as do all languages, but we're not dealing with log-cabin construction methods that have been around for 100's of years, we're dealing with bleeding-edge software development.

In the end, use what you like and stop trying to tell everyone else why they're right or wrong. Everyone else might do well to not read insults into otherwise constructive criticism or airing of opinions, and not take those opinions personally.

Alberto, thanks man. Can't believe I hadn't discovered the if ternary operator in VB.Net.



'McFly' on Fri, 06 Nov 2009 14:30:46 GMT, sez:

Heh, heh...fez with a brim.



'spar' on Wed, 14 Apr 2010 04:53:44 GMT, sez:

Cant believe people would bitch about ; to end your lines in c#.

Surely it's more sensible to have the ability to structure long method calls or strings without _ at the end of each line.

One of the annoying things about vb to me is the :

if 1=1 then dont need an end if on same line

or that "else if" is different to "elseif", yeah thats clear :p (although certainly not worse than counting {}'s in vi...)

Anyway, thx for the ternary if !



'Joel' on Fri, 07 May 2010 01:34:37 GMT, sez:

Thanks for the proper ternary If! I may search through our entire solution to weed out any badly used IIf functions. While typing the proper one, intellisense gave me this:
If(TestExpression As Object, FalsePart As Object) As Object
This isn't really a ternary If like the former, but it sounds like a shortcut to using

If Foo is Nothing Then
Foo = new MyObject().ToString()
Else
Foo.ToString()
End If

However from my experience long winded code like the latter is more readable and with codefile tidies like #region, I think its worth using whatever your team finds more readable at the end of the day.



'Joel' on Fri, 07 May 2010 01:36:34 GMT, sez:

eh nvm that bad coding example I didn't mean to assing a String to Foo, just trying to point out there is an easier way to avoid null pointer exceptions



'Abhishek Tiwari' on Tue, 29 Jun 2010 15:30:38 GMT, sez:

I am using VS 2010. I created a console application and I did not find any error on following statement

Dim divideBy As Integer = 0
Dim myNumber As Integer = 4
Dim result As Integer = IIf(divideBy = 0, 0, myNumber / divideBy)
Console.WriteLine(result)
Console.ReadLine()

I don't find any exception thrown running as above. I am not sure where is the issue. Although if i try this
Dim result As Integer = IIf(divideBy <> 0, 0, myNumber / divideBy)
it surely throws arithmatic overflow exception which is quite expected.



'Abhishek Tiwari' on Tue, 29 Jun 2010 15:40:26 GMT, sez:

I am using VS 2010. I created a console application and I did not find any error on following statement

Dim divideBy As Integer = 0
Dim myNumber As Integer = 4
Dim result As Integer = IIf(divideBy = 0, 0, myNumber / divideBy)
Console.WriteLine(result)
Console.ReadLine()

I don't find any exception thrown running as above. I am not sure where is the issue. Although if i try this
Dim result As Integer = IIf(divideBy <> 0, 0, myNumber / divideBy)
it surely throws arithmatic overflow exception which is quite expected.



'Abhishek Tiwari' on Tue, 29 Jun 2010 15:42:00 GMT, sez:

VB.Net 10 has come up ternary operator within IF statement.

Dim d = If(dict.ContainsKey("A"), dict("A"), Nothing)
it will evaluate only true or false part based on the expression.



'Tracy' on Mon, 09 May 2011 18:19:52 GMT, sez:

Alberto: THANK YOU! THANK YOU! THANK YOU! For pointing out the new IF() syntax for VB9! That saved me a LOT of grief and extra coding.



'gerdi' on Tue, 08 May 2012 06:41:52 GMT, sez:

WOW this site is SOOO badly laid out , for goodness sake man put some padding on the page!!!

it sucks because i am sure there is a wealth of information on this site




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. Incivility is not tolerated, such comments are deleted.

 

I'm the co-author of TimeSnapper, 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.

 

NimbleText - FREE text manipulation and data extraction

NimbleText is a Powerful FREE Tool

I wrote this, and use it every day for:

  • extracting data from text
  • manipulating text
  • generating code

It makes you look awesome. You should use NimbleText, you handsome devil!

 

Articles

The Canine Pyramid The Canine Pyramid
Humans: A Tragedy. Humans: A Tragedy.
ACK! ACK!
OfficeQuest... Gamification for the Office Suite OfficeQuest... Gamification for the Office Suite
New product launch: NimbleSET New product launch: NimbleSET
Programming The Robot from Diary of a Wimpy Kid Programming The Robot from Diary of a Wimpy Kid
Happy new year 2014 Happy new year 2014
Downtime as a service Downtime as a service
The Shape of Your Irrationality The Shape of Your Irrationality
This is why I don't go to nice restaurants any more. This is why I don't go to nice restaurants any more.
A flowchart of what programmers do at work all day A flowchart of what programmers do at work all day
The Telepresent Man. The Telepresent Man.
Interview with an Ex-Microsoftie. Interview with an Ex-Microsoftie.
CRUMBS! Commandline navigation tool for Powershell CRUMBS! Commandline navigation tool for Powershell
Little tool for making Amazon affiliate links Little tool for making Amazon affiliate links
Extracting a Trello board as markdown Extracting a Trello board as markdown
hgs: Manage Lots of Mercurial Projects Simultaneously hgs: Manage Lots of Mercurial Projects Simultaneously
You Must Get It! You Must Get It!
AddDays: A Very Simple Date Calculator AddDays: A Very Simple Date Calculator
Google caught in a lie. Google caught in a lie.
NimbleText 2.0: More Than Twice The Price! NimbleText 2.0: More Than Twice The Price!
A Computer Simulation of Creative Work, or 'How To Get Nothing Done' A Computer Simulation of Creative Work, or 'How To Get Nothing Done'
NimbleText 1.9 -- BoomTown! NimbleText 1.9 -- BoomTown!
Line Endings. Line Endings.
**This** is how you pivot **This** is how you pivot
Art of the command-line helper Art of the command-line helper
Go and read a book. Go and read a book.
Slurp up mega-traffic by writing scalable, timeless search-bait Slurp up mega-traffic by writing scalable, timeless search-bait
Do *NOT* try this Hacking Script at home Do *NOT* try this Hacking Script at home
The 'Should I automate it?' Calculator The 'Should I automate it?' Calculator

Archives Complete secretGeek Archives

TimeSnapper -- Automated Screenshot Journal TimeSnapper: automatic screenshot journal

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
Universal Troubleshooting checklist Universal Troubleshooting Checklist
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Realtime CSS Editor, in a browser RealTime Online CSS Editor
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 little schemer


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

Recommended blogs

Jeff Atwood
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink

InfoText - amazing search for SharePoint
LogEnvy - event logs made sexy
Computer, Unlocked. A rapid computer customization resource
Aussie Bushwalking
BrisParks :: best parks for kids in brisbane
PhysioTec, Brisbane Specialist Physiotherapy & Pilates
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: Leon Bambrick 2003 .: privacy

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