<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="VB6Parse Library Reference - iif - Logic">
<title>iif - Logic - VB6Parse Library Reference</title>
<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/docs-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="../../../assets/js/theme-switcher.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body>
<header class="docs-header">
<div class="container">
<h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/logic/index.html">Logic</a> / iif</h1>
<p class="tagline">VB6 Library Reference</p>
</div>
</header>
<nav class="docs-nav">
<div class="container">
<a href="../../../index.html">Home</a>
<a href="../../../library/index.html">Library Reference</a>
<a href="../../../documentation.html">Documentation</a>
<a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
<a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<span class="theme-icon">🌙</span>
</button>
</div>
</nav>
<main class="container">
<article class="library-item">
<h1 id="iif-function">IIf Function</h1>
<p>Returns one of two parts, depending on the evaluation of an expression.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">IIf(expr, truepart, falsepart)</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><code>expr</code> (Required): Expression you want to evaluate</li>
<li><code>truepart</code> (Required): Value or expression returned if <code>expr</code> is True</li>
<li><code>falsepart</code> (Required): Value or expression returned if <code>expr</code> is False</li>
</ul>
<h2 id="return-value">Return Value</h2>
<p>Returns <code>truepart</code> if <code>expr</code> evaluates to True; otherwise returns <code>falsepart</code>. The return type
is <code>Variant</code> and depends on the types of <code>truepart</code> and <code>falsepart</code>.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>IIf</code> function provides inline conditional evaluation:
- Always evaluates BOTH <code>truepart</code> and <code>falsepart</code> regardless of the condition result
- This can cause side effects if either part contains function calls or property accesses
- Returns <code>Variant</code> type, which may require explicit type conversion
- Can nest <code>IIf</code> calls for multiple conditions (though readability suffers)
- If <code>expr</code> is Null, the function returns Null
- Unlike <code>If...Then...Else</code> statements, <code>IIf</code> is an expression that returns a value
- Useful for inline assignments, but beware of evaluation side effects
- Consider using <code>If...Then...Else</code> for complex logic or when side effects matter</p>
<h2 id="typical-uses">Typical Uses</h2>
<ol>
<li><strong>Inline Conditionals</strong>: Simple conditional value assignment in one line</li>
<li><strong>String Formatting</strong>: Choose between different string representations</li>
<li><strong>Calculated Fields</strong>: Conditional calculations in expressions</li>
<li><strong>Default Values</strong>: Provide fallback values for empty or null data</li>
<li><strong>Display Logic</strong>: Choose display text based on conditions</li>
<li><strong>Data Validation</strong>: Return appropriate values based on validation results</li>
</ol>
<h2 id="basic-usage-examples">Basic Usage Examples</h2>
<pre><code class="language-vbnet">' Example 1: Simple conditional assignment
Dim result As String
result = IIf(age >= 18, "Adult", "Minor")
' Example 2: Numeric comparison
Dim status As String
status = IIf(score >= 60, "Pass", "Fail")
' Example 3: Null handling
Dim display As String
display = IIf(IsNull(value), "N/A", CStr(value))
' Example 4: Sign determination
Dim sign As String
sign = IIf(number >= 0, "+", "-")</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<pre><code class="language-vbnet">' Pattern 1: Choose singular or plural
Function FormatCount(count As Long, singular As String, plural As String) As String
FormatCount = count & " " & IIf(count = 1, singular, plural)
End Function
' Usage: FormatCount(5, "item", "items") => "5 items"
' Pattern 2: Min/Max selection
Function Min(a As Double, b As Double) As Double
Min = IIf(a < b, a, b)
End Function
Function Max(a As Double, b As Double) As Double
Max = IIf(a > b, a, b)
End Function
' Pattern 3: Safe division
Function SafeDivide(numerator As Double, denominator As Double) As Variant
SafeDivide = IIf(denominator <> 0, numerator / denominator, Null)
End Function
' Pattern 4: Empty string default
Function GetDisplayName(name As String) As String
GetDisplayName = IIf(Len(Trim$(name)) > 0, name, "(unnamed)")
End Function
' Pattern 5: Range clamping
Function Clamp(value As Long, minVal As Long, maxVal As Long) As Long
Clamp = IIf(value < minVal, minVal, IIf(value > maxVal, maxVal, value))
End Function
' Pattern 6: Boolean to integer
Function BoolToInt(value As Boolean) As Integer
BoolToInt = IIf(value, 1, 0)
End Function
' Pattern 7: Sign function
Function Sign(value As Double) As Integer
Sign = IIf(value > 0, 1, IIf(value < 0, -1, 0))
End Function
' Pattern 8: Null coalescing
Function Coalesce(value As Variant, defaultValue As Variant) As Variant
Coalesce = IIf(IsNull(value) Or IsEmpty(value), defaultValue, value)
End Function
' Pattern 9: Conditional formatting
Function FormatBalance(balance As Currency) As String
FormatBalance = IIf(balance < 0, _
"(" & Format$(Abs(balance), "Currency") & ")", _
Format$(balance, "Currency"))
End Function
' Pattern 10: Toggle value
Function Toggle(current As Boolean) As Boolean
Toggle = IIf(current, False, True)
End Function</code></pre>
<h2 id="advanced-usage-examples">Advanced Usage Examples</h2>
<pre><code class="language-vbnet">' Example 1: Grade calculator with nested IIf
Function GetGrade(score As Double) As String
GetGrade = IIf(score >= 90, "A", _
IIf(score >= 80, "B", _
IIf(score >= 70, "C", _
IIf(score >= 60, "D", "F"))))
End Function
' Example 2: Complex string builder
Function BuildMessage(userName As String, isAdmin As Boolean, messageCount As Long) As String
BuildMessage = "Welcome " & IIf(Len(userName) > 0, userName, "Guest") & _
IIf(isAdmin, " (Admin)", "") & _
IIf(messageCount > 0, " - You have " & messageCount & " message" & _
IIf(messageCount = 1, "", "s"), "")
End Function
' Example 3: Data validation with IIf
Function ValidateAndFormat(input As String, Optional maxLen As Long = 50) As String
Dim cleaned As String
cleaned = Trim$(input)
ValidateAndFormat = IIf(Len(cleaned) = 0, "", _
IIf(Len(cleaned) > maxLen, _
Left$(cleaned, maxLen) & "...", _
cleaned))
End Function
' Example 4: Status indicator with color codes
Function GetStatusDisplay(value As Double, threshold As Double) As String
Dim status As String
Dim color As String
status = IIf(value >= threshold, "OK", "WARNING")
color = IIf(value >= threshold, "Green", "Red")
GetStatusDisplay = "[" & color & "] " & status & " (" & value & ")"
End Function
' Example 5: Conditional object creation (DANGEROUS - both parts evaluate!)
' WARNING: This pattern has side effects!
Function GetConnection(useLocal As Boolean) As Object
' BOTH CreateLocalConnection AND CreateRemoteConnection will execute!
' Use If...Then...Else instead for object creation
Set GetConnection = IIf(useLocal, CreateLocalConnection(), CreateRemoteConnection())
End Function
' Example 6: Safe property access
Function GetPropertyValue(obj As Object, propertyName As String, defaultValue As Variant) As Variant
On Error Resume Next
Dim value As Variant
value = CallByName(obj, propertyName, VbGet)
If Err.Number = 0 Then
GetPropertyValue = IIf(IsNull(value), defaultValue, value)
Else
GetPropertyValue = defaultValue
End If
On Error GoTo 0
End Function</code></pre>
<h2 id="error-handling">Error Handling</h2>
<p>The <code>IIf</code> function itself rarely raises errors, but be aware of:
- <strong>Type Mismatch (Error 13)</strong>: Can occur if the result type doesn't match the receiving variable
- <strong>Evaluation Errors</strong>: Both <code>truepart</code> and <code>falsepart</code> are always evaluated, so errors in either will occur
- <strong>Null Propagation</strong>: If <code>expr</code> is Null, <code>IIf</code> returns Null
- <strong>Division by Zero</strong>: Can occur if either part contains division and is evaluated</p>
<pre><code class="language-vbnet">' WRONG - Both divisions execute regardless of condition!
result = IIf(denominator <> 0, numerator / denominator, numerator / 1)
' If denominator is 0, division by zero error still occurs in first part
' CORRECT - Use If...Then...Else for conditional execution
If denominator <> 0 Then
result = numerator / denominator
Else
result = numerator / 1
End If</code></pre>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li><strong>Both Branches Evaluate</strong>: <code>IIf</code> always evaluates both <code>truepart</code> and <code>falsepart</code></li>
<li><strong>Function Call Overhead</strong>: <code>IIf</code> has function call overhead vs. <code>If...Then...Else</code></li>
<li><strong>Variant Boxing</strong>: Results are <code>Variant</code> type, which may require type conversion</li>
<li><strong>Nested Performance</strong>: Deeply nested <code>IIf</code> calls can be slow and hard to read</li>
<li><strong>Use <code>If...Then...Else</code> When</strong>: Either branch has expensive operations or side effects</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<ol>
<li><strong>Avoid Side Effects</strong>: Don't use <code>IIf</code> when either part has side effects (function calls, object creation, I/O)</li>
<li><strong>Keep It Simple</strong>: Use <code>IIf</code> for simple value selection only</li>
<li><strong>Limit Nesting</strong>: Avoid deeply nested <code>IIf</code> calls (use <code>Select Case</code> or <code>If...Then...Else</code> instead)</li>
<li><strong>Type Safety</strong>: Be aware of <code>Variant</code> return type and convert explicitly if needed</li>
<li><strong>Readability</strong>: If <code>IIf</code> makes code harder to read, use <code>If...Then...Else</code></li>
<li><strong>Document Expectations</strong>: When using <code>IIf</code>, document that both branches evaluate</li>
</ol>
<h2 id="when-not-to-use-iif">When NOT to Use <code>IIf</code></h2>
<pre><code class="language-vbnet">' DON'T: Object creation (both execute!)
Set obj = IIf(condition, New ClassA, New ClassB)
' DON'T: Functions with side effects (both execute!)
result = IIf(condition, LogAndReturn("A"), LogAndReturn("B"))
' DON'T: Error-prone operations (both execute!)
value = IIf(x <> 0, 100 / x, 0) ' Division by zero still occurs!
' DON'T: Complex nested logic (hard to read)
result = IIf(a, IIf(b, IIf(c, 1, 2), IIf(d, 3, 4)), IIf(e, 5, 6))
' DO: Use If...Then...Else instead
If condition Then
Set obj = New ClassA
Else
Set obj = New ClassB
End If</code></pre>
<h2 id="comparison-with-other-approaches">Comparison with Other Approaches</h2>
<table>
<thead>
<tr>
<th>Approach</th>
<th>Evaluates Both</th>
<th>Return Type</th>
<th>Use Case</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>IIf</code></td>
<td>Yes</td>
<td><code>Variant</code></td>
<td>Simple inline value selection</td>
</tr>
<tr>
<td><code>If...Then...Else</code></td>
<td>No</td>
<td>Any</td>
<td>Conditional execution, side effects</td>
</tr>
<tr>
<td><code>Select Case</code></td>
<td>No</td>
<td>Any</td>
<td>Multiple conditions</td>
</tr>
<tr>
<td><code>Choose</code></td>
<td>Yes</td>
<td><code>Variant</code></td>
<td>Index-based selection</td>
</tr>
</tbody>
</table>
<h2 id="platform-and-version-notes">Platform and Version Notes</h2>
<ul>
<li>Available in all VB6 versions</li>
<li>Consistent behavior across Windows platforms</li>
<li>VBA also includes <code>IIf</code> with identical behavior</li>
<li>Always returns <code>Variant</code> type</li>
<li>Evaluation of both branches is by design, not a bug</li>
</ul>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Cannot short-circuit evaluation (both parts always execute)</li>
<li>Returns Variant type (requires explicit conversion for strong typing)</li>
<li>Not suitable for conditional execution (use <code>If...Then...Else</code>)</li>
<li>Nested <code>IIf</code> calls quickly become unreadable</li>
<li>Cannot handle multiple conditions as cleanly as <code>Select Case</code></li>
<li>May have performance overhead compared to <code>If...Then...Else</code></li>
</ul>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>If...Then...Else</code>: Statement for conditional execution with short-circuit evaluation</li>
<li><code>Choose</code>: Returns value from list based on numeric index (also evaluates all parts)</li>
<li><code>Switch</code>: Returns first value whose expression is True (evaluates sequentially)</li>
<li><code>Select Case</code>: Multi-condition statement with short-circuit evaluation</li>
</ul>
</article>
<div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
<p>
<a href="index.html">← Back to Logic</a> |
<a href="../index.html">View all functions</a>
</p>
</div>
</main>
<footer>
<div class="container">
<p>© 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
</div>
</footer>
</body>
</html>