Table of Contents

RDC00209: Boolean assigned in If…Else

Severity: Information  ·  Family: RDC (Rubberduck Core analyzers)  ·  Raised by: BooleanAssignedInIfElseAnalyzer

Each branch of an If…Else assigns a Boolean literal to the same variable: True in one and False in the other (MS-VBAL §5.4.2.8 If Statement). The If can be written on several lines or on one.

The variable receives the truth value of the condition, or of its negation. One assignment of the condition says the same in a single statement.

Each branch must hold that one assignment and nothing else. An ElseIf, a second statement, a Set, or two different targets make it something else, and are not reported. The target can be a variable, a member of an object (Me.Done, .Enabled in a With block), an element of an array (flags(i)), or a member of what a call returns (Range("A1").Locked).

A condition that is not a Boolean (If n Then) is converted with CBool in the assignment: bar = CBool(n), or bar = Not CBool(n). Not n negates each bit of a number: Not 1 is -2, which is True.

A condition that can be Null (a Variant, or a comparison with one) is different again. The If takes Null as False and runs its Else branch, where CBool(Null), and the assignment of Null to a Boolean, raise error 94.

The finding is the header of the If.

How it is raised

Situation Example Resolution
True in the If branch, False in the Else. If foo > 0 Then
bar = True
Else
bar = False
End If
bar = foo > 0
False in the If branch, True in the Else. If foo > 0 Then
bar = False
Else
bar = True
End If
bar = Not (foo > 0)
The same on one line. If foo > 0 Then bar = True Else bar = False bar = foo > 0

Quick fix

Where the condition is a Boolean whatever its operands hold, the diagnostic comes with a quick fix, Assign the condition to '…' or Assign Not the condition to '…'. It replaces the block with the assignment, and the program does the same. Such a condition is an Is or TypeOf…Is operation, True or False, or Not, And, Or, Xor, Eqv, Imp and parentheses of those (If Not (o Is Nothing) Then).

Another condition, a comparison among them, may be Null or a number, and no quick fix is offered. The quick fix is not offered either when a comment is written in the block, nor for a target with arguments (flags(i), Range("A1").Locked): the If evaluates the condition before the arguments, and a single assignment can evaluate them first, so a call in either could see a different value.

See also


ACCUEIL • HOME | ℹ️ BIENVENUE • WELCOME | 🧩 BÂTISSONS • BUILD | RD-VBAL | SDK | 🌐 rubberduckvba.ca