IIf Function

Returns one of two objects, depending on the evaluation of an expression.

Note

Visual Basic 2008 introduces a new If operator that uses short-circuit evaluation. For more information, see If Operator.

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

Parameters

  • Expression
    Required. Boolean. The expression you want to evaluate.

  • TruePart
    Required. Object. Returned if Expression evaluates to True.

  • FalsePart
    Required. Object. Returned if Expression evaluates to False.

Example

This example uses the IIf function to evaluate the testMe parameter of the checkIt procedure and returns the word "Large" if the amount is greater than 1000; otherwise, it returns the word "Small".

Function checkIt(ByVal testMe As Integer) As String 
    Return CStr(IIf(testMe > 1000, "Large", "Small"))
End Function

Note that if Option Strict is On, you must use the CStr keyword to explicitly convert the return from Object to String.

Because the IIf function does not use short-circuit evaluation, it always evaluates all three of its arguments. The If operator evaluates its first argument and, depending on the value of the first argument, either the second or the third argument. In the following example, using the IIf function causes a run-time divide-by-zero error when the divisor is 0, but using the If operator does not because the second argument is not evaluated in that case.

number = 12

' When the divisor is not 0, both If and IIf return 4. 
Dim divisor = 3
Console.WriteLine(If(divisor <> 0, number \ divisor, 0))
Console.WriteLine(IIf(divisor <> 0, number \ divisor, 0))

' When the divisor is 0, IIf causes a run-time error, but If does not.
divisor = 0
Console.WriteLine(If(divisor <> 0, number \ divisor, 0))
' Console.WriteLine(IIf(divisor <> 0, number \ divisor, 0))

For more information about the If operator, see If Operator.

Requirements

Namespace: Microsoft.VisualBasic

Module: Interaction

Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)

See Also

Reference

Option Strict Statement

Type Conversion Functions

Choose Function

If...Then...Else Statement (Visual Basic)

Select...Case Statement (Visual Basic)

Switch Function

If Operator

Change History

Date

History

Reason

August 2008

Added an example to explain short-circuit evaluation.

Customer feedback.