If Statements
Prerequisites: Operators and comparisons
If ... Then ... End If runs code only when a condition is True:
Module Program
Sub Main()
Dim temperature = 31
If temperature > 30 Then
Console.WriteLine("Stay in the shade")
ElseIf temperature > 15 Then
Console.WriteLine("Enjoy the weather")
Else
Console.WriteLine("Take a jacket")
End If
End Sub
End Module
Stay in the shade
ElseIfis one word.- The first condition that's
Truewins; the rest are skipped. - Every block
Ifneeds a matchingEnd If.
Single-line If
Short checks can go on one line, without End If:
Module Program
Sub Main()
Dim stock = 3
If stock < 5 Then Console.WriteLine("Low stock: reorder!")
If stock = 0 Then Console.WriteLine("Sold out") Else Console.WriteLine($"{stock} left")
End Sub
End Module
Low stock: reorder!
3 left
Use the single-line form only for very simple statements; the block form is easier to read and to extend.
Nested conditions
Module Program
Sub Main()
Dim age = 25
Dim hasTicket = True
If age >= 18 Then
If hasTicket Then
Console.WriteLine("Welcome in")
Else
Console.WriteLine("Please buy a ticket")
End If
Else
Console.WriteLine("Adults only")
End If
' Often clearer combined:
If age >= 18 AndAlso hasTicket Then Console.WriteLine("Welcome in (again)")
End Sub
End Module
Welcome in
Welcome in (again)
Common mistakes
- Forgetting
Thenat the end of the condition line. - Using
Andinstead ofAndAlsowhen the second check depends on the first. - Writing
If x = True Then— just writeIf x Then.
Practice
Write a program that stores a score and prints "A" for 90 or more,
"B" for 80 or more, "C" for 70 or more, and "F" otherwise. Test it
with 84.
Show solution
Module Program
Sub Main()
Dim score = 84
Dim grade As String
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
ElseIf score >= 70 Then
grade = "C"
Else
grade = "F"
End If
Console.WriteLine($"Score {score}: {grade}")
End Sub
End Module
Score 84: B