Background
The If...Else operator is a fundamental control tool present in all versions of Visual Basic, starting from the very first release. Its development has progressed from simple linear branching to an expanded syntax with support for ElseIf, End If, and logical expressions of any complexity.
Problem
Many people make mistakes due to incorrect formatting or nesting of conditions, misuse ElseIf, which complicates readability and leads to elusive logical errors. Beginners often confuse When and ElseIf, as well as make mistakes by duplicating logic.
Solution
Use If...ElseIf...Else...End If for readable construction of nested conditions. Always group relevant conditions, avoid repetitive checks and redundant constructs. For complex conditions, it is better to use logical operators (AndAlso, OrElse).
Example code:
Dim age As Integer = 22 If age < 18 Then Console.WriteLine("Minor") ElseIf age < 65 Then Console.WriteLine("Adult") Else Console.WriteLine("Senior") End If
Key features:
ElseIf blocks enhances readability.What happens if End If is not used in multi-line If constructs?
Compilation error. All multi-line constructs require End If. Improvements have occurred with the emergence of single-line If, for example:
If x > 0 Then y = 1 Else y = -1
Can ElseIf have its own Else?
No. Only one Else can be used in a chain of conditions, and it belongs to the entire If block. For example:
If x = 1 Then ... ElseIf x = 2 Then ... Else ... End If
What is the difference between Or and OrElse?
Or always evaluates both conditions, while OrElse only evaluates the second if the first is false. Use OrElse for short-circuiting.
Multilevel nesting of If, where each condition is not supplied with Else, and there is insufficient documentation, leads to errors when adding new branches.
Pros:
Cons:
Using readable ElseIf with explanations, combining related conditions, completing all branches.
Pros:
Cons: