Monday, May 16, 2011

Inline IFs

Have you ever wanted to be able to conditionally add something to the middle of a statement without lots of if-then or select statements? Here's a trick that I've used in many of my own projects.


In a module, define a method (IIF = Inline IF):

Name: IIF
Parameters: Condition as Boolean, TrueValue as Variant, FalseValue as Variant
Returns: Variant

If Condition Then
Return TrueValue
Else
Return FalseValue
End If

Here's a quick example of how you might use this in your code. Imagine you wanted to display a different confirmation message based on how many records the program was about to delete:

Dim msg as String = "Are you sure you want to delete " + IIF(n=1,"this record","these records") + "?"

If MsgBox(msg,4) = 6 Then
//…Delete Record(s) here…
End If

If n=1, the message displayed will be:

"Are you sure you want to delete this record?"

Otherwise, it will read:

"Are you sure you want to delete these records?"


4 comments:

Thomas said...

Neat.

It should be noted, though, that this may lead to inefficient performance as using the IFF() function will have to "calculate" all arguments, while using if ... else ... end will only calculate the one branch that's chosen by the if clause.
Usually not a problem to use IFF() but one should be aware of the implications.

General said...

Since I started using RS, I've been wondering why it doesn't already have the Immediate If (ok... "Inline If") functionality already built into the language. It's been a standard of VB forever, and I always used it extensively.

Thomas said...

Huh, my "smart" comment got lost, too. Oh well.

LazyGator said...

Thanks for the tip, Greg!