rachelreese's blog

One Rachii's take on .NET, Phoenix, and some unrelated, potentially completely random things.

Along the lines of AndAlso and OrElse...

I remind everyone of “IIf“.  Another tremendously useful little bit of code that I use all the time.  If your If-statement is designed to set a single variable, like this one:

If Request("index") Is Nothing Then
  myVariable = 0
Else
  myVariable = Convert.ToInt32(Request("index")))
End If

then you can easily convert it to a single line, as follows! 

(thanks Kartal)  myVariable = IIf(Request("index") Is Nothing, 0, Convert.ToInt32(Request("index")))

The documentation (if it's installed: ms-help://MS.NETFrameworkSDKv1.1/vblr7net/html/vafctiif.htm) shows that it's used like this:

Public Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, ByVal FalsePart As Object) As Object

(example stolen from the TimeTracker Starter Kit: line 48 of Usercontrols\Banner.ascx.)  I again can't think of any good reason not to use it. 

Comments

Kartal Guner said:

What is the IIf setting? You probably just left off the "myVariable ="

The only thing is that the if.. else...end is easier to read. Really though if your adverse to verbose code should you really be using VB.NET?
# October 3, 2003 6:19 PM

Rachel Reese said:

Oops, thanks. Fixed that. I'm not going to justify why I do or don't use any language. It's a waste of everybody's time. I offer this tip to possibly help someone who *is* coding in VB.NET.
# October 3, 2003 6:38 PM

denny said:

well imho semi-verbose basic is a lot better to fllow then over cryptic stuff I see sometimes.

and if you want terse code try WebBase -- funky thing based on smalltalk where every expression is stack based notation....

real programers tool there.... you have to be a hard core hacker to even rerad webbase code at all....

# October 3, 2003 8:42 PM

Kartal Guner said:

Sorry, I wasn't trying to put down VB. I just thought that the regular if then else is easier to read. Does iif give any performance advantage like andalso or orelse?
# October 4, 2003 10:07 AM

Rachel Reese said:

heh -- I'll have to check out WebBase.

You are right, IIf is more dfficult to read, if you're not used to it. It's just a convention, really. I personally think it's a handy little tool, and use it when I can.

I had thought that IIf would have a performance boost, but I can only find one page on Google (http://www.aivosto.com/project/help/problemdetection-style.html) that mentions performance either way, which says:
IIf / Switch / Choose function found. These functions are considered bad programming style because of functionality, optimization and readability issues. All conditions and branches of IIf / Switch / Choose are always executed resulting in longer execution time and possible unwanted side-effects. Switch and Choose may return an unwanted Null. Use Select Case or If..End If instead. IIF, SWITCH, CHOOSE

So, I guess it's not recommended.
# October 4, 2003 4:08 PM

Mike said:

Following on from Rachel's last comment..

IIRC in VB6 there was an issue with the IIF function in that it always executed every expression supplied to it. So the following would fail if objTest was Nothing :

myStr = IIF(objTest Is Nothing, "", objTest.Output)

And this would need you expand it out to :

If objTest Is Nothing Then
myStr = ""
Else
myStr = objTest.Output
End If
# October 9, 2003 4:22 AM

Mark said:

If anybody cares, C# has an immediate if also:

myVariable = (Request["index"] == null) ? 0 : Convert.ToInt32(Request["index"]);

Just thought I'd point that out, it took me a while to find it when I first started learning C#
# October 9, 2003 3:13 PM

Peter said:

I never use the IIf construct in VB/VBScript, nor the ? operator in C++/C#. It has been my experience that sometimes you want to add a debug.print type of statement in one of the branches, and that frequently involves having to rewrite the IIF as an if then else block, then back again (if you remember to). Also, when I used to use these constructs, I would sometimes forget where the true thing went and swap them around. Writing code in a way that keeps me less likely to make mistakes is a hard habit to get into. An example in C/C++/C# of that sort of habit would be:

if( SOME_CONSTANT == SomeVariable)

SOME_CONSTANT == SomeVariable (valid comparison)
SOME_CONSTANT = SomeVariable (invalid, compiler catches it)
SomeVariable == SOME_CONSTANT (valid comparison)
SomeVariable = SOME_CONSTANT (valid assignment, always true, only LINT will catch it)

Since I know that I have had a habit of leaving off one equal sign, doing SomeVariable == SOME_CONSTANT becomes a potential error. SomeVariable = SOME_CONSTANT pretty much always evaluates true (it evaluates to false when you run out of memory and can't do the assignment, or maybe it is an IO register and you are writing to a read-only port) which is not what one is looking for. I know some language lawyer somewhere will claim/argue they intended to write such a thing, sometime in the last million years, but the vast majority of people who write it left off one equal sign, and in my 25 years of writing code I have never meant to do it intentionally.

Personally, I will be using neither AndAlso, nor OrElse. If I need to do comparisons with short circuiting operators, I will be nesting the if..then..else blocks. Adding something that looks cool but can introduce more errors is not a good idea in my book.
# October 10, 2003 4:00 PM

Chris said:

From VB.Net in Nutshell, p 374: "the performance of IIF from VB6 to VB.NET has improved by 100%. At the same time, the function is over 300 times slower than an IF statement under VB.NET"

IIF Function|If Statement
-------|------------|-------------
VB 6 | 11.09 | 0.52
VB.NET | 6.12 | 0.02

*The avg # of secs required to call the IIF function a million times VS avg # of secs required to call an "If..ElseIf...Else...EndIF" statement a million times
# October 13, 2003 4:42 PM

Rachel Reese said:

good god. Thank you Chris.
# October 13, 2003 4:57 PM

Cachucho said:

What about that:

Select case False
case Restriction1Ok(data)
case Restriction2Ok(data)
case Restriction3Ok(data)
case Restriction4Ok(data)
case else
ThereIsAaProblem()
end Select

# October 28, 2003 2:42 PM

Chip said:

There are places where I can only plug in a value or expression and not lines of code. In those cases IIf comes in very handy.
# February 21, 2004 10:32 AM

SunDog said:

For those of you still undecided as to which method to use, i.e. IIf vs If..Then..Else, please use the following function:

Public Function gfToIIfOrNotToIIf(bAllBranchesOKToExecute As Boolean, bResourceAvailabilityHigh As Boolean, bReadabilityNotAnIssue As Boolean, bSoonToHandOffProject As Boolean) As String
gfTest = IIf(bAllBranchesOKToExecute, "Use IIf", IIf(bResourceAvailabilityHigh, "Use IIf", IIf(bReadabilityNotAnIssue, "Use IIf", IIf(bSoonToHandOffProject, "Use IIf", "Use If..Then..Else block"))))
End Function
# May 11, 2004 5:29 PM

Rachel Reese said:

LOL, that's awesome.
# May 11, 2004 5:31 PM

SunDog said:

Oops....a little typo:

Function should read:


Public Function gfToIIfOrNotToIIf(bAllBranchesOKToExecute As Boolean, bResourceAvailabilityHigh As Boolean, bReadabilityNotAnIssue As Boolean, bSoonToHandOffProject As Boolean) As String
gfToIIfOrNotToIIf = IIf(bAllBranchesOKToExecute, "Use IIf", IIf(bResourceAvailabilityHigh, "Use IIf", IIf(bReadabilityNotAnIssue, "Use IIf", IIf(bSoonToHandOffProject, "Use IIf", "Use If..Then..Else block"))))
End Function
# May 11, 2004 5:32 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)