Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Control Flow and Procedures

If Statements and Select Case

Make decisions in Visual Basic .NET with If/ElseIf/Else, single-line If, the If() operator and Select Case with ranges, lists and comparisons, plus guard clauses and common mistakes.

Programs become useful when they can choose between actions. VB.NET has two main decision statements: If, which tests Boolean conditions, and Select Case, which compares one value against many possibilities. Both read almost like English. Listings are VB.NET (read-only); runnable C# stand-ins mirror them so you can test the logic.

If, ElseIf and Else

VB
Dim temperature As Integer = 28

If temperature >= 30 Then
    Console.WriteLine("Hot")
ElseIf temperature >= 20 Then
    Console.WriteLine("Warm")
ElseIf temperature >= 10 Then
    Console.WriteLine("Cool")
Else
    Console.WriteLine("Cold")
End If

Conditions are checked from top to bottom and the first true branch runs. ElseIf is one word, Then ends the condition, and End If (two words) closes the whole block. Else is optional.

A one-line form exists for tiny actions:

VB
If isLoggedIn Then Console.WriteLine("Welcome back")
If count = 0 Then Console.WriteLine("empty") Else Console.WriteLine("not empty")

Prefer the block form for anything beyond one short statement: it is easier to extend and to debug.

Combining conditions

Use AndAlso, OrElse and Not (see Operators and Expressions):

VB
Dim age As Integer = 25
Dim hasTicket As Boolean = True

If age >= 18 AndAlso hasTicket Then
    Console.WriteLine("Enter")
ElseIf Not hasTicket Then
    Console.WriteLine("Buy a ticket first")
Else
    Console.WriteLine("Too young")
End If

Guard clauses reduce nesting

Instead of wrapping the main logic in a deep pyramid, exit early:

VB
Function Discount(price As Decimal, isMember As Boolean) As Decimal
    If price <= 0D Then Return 0D
    If Not isMember Then Return price

    Return price * 0.9D
End Function
C# Stand-in (C#): chained decisions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The If() expression

When you only need to choose a value, the If operator is shorter than a block:

VB
Dim label As String = If(temperature >= 20, "warm", "cool")

Remember If(a, b, c) evaluates only the branch it needs. Avoid the old IIf function, which always evaluates both.

Select Case

Select Case evaluates an expression once and runs the first matching Case. It is clearer than a long ElseIf chain when you compare one value many ways.

VB
Dim day As Integer = 6

Select Case day
    Case 1
        Console.WriteLine("Monday")
    Case 2, 3, 4, 5
        Console.WriteLine("Midweek")
    Case 6 To 7
        Console.WriteLine("Weekend")
    Case Is < 1, Is > 7
        Console.WriteLine("Invalid day")
    Case Else
        Console.WriteLine("Not reachable")
End Select

A Case can hold:

  • a single value (Case 1)
  • a list separated by commas (Case 2, 3, 4, 5)
  • a range with To (Case 6 To 7, inclusive on both ends)
  • a comparison with Is (Case Is >= 90)

Case Else handles everything that is left and should usually be present. There is no fall-through: after a branch runs, control leaves the Select Case, so no break is needed. Use Exit Select to leave a branch early.

Select Case with strings and ranges

VB
Dim score As Integer = 83

Select Case score
    Case Is >= 90
        Console.WriteLine("A")
    Case 80 To 89
        Console.WriteLine("B")
    Case 70 To 79
        Console.WriteLine("C")
    Case Else
        Console.WriteLine("Needs work")
End Select

Dim command As String = "SAVE"
Select Case command.ToLowerInvariant()
    Case "open", "load"
        Console.WriteLine("Opening")
    Case "save"
        Console.WriteLine("Saving")
    Case Else
        Console.WriteLine("Unknown command")
End Select

Ranges and Is comparisons are where Select Case is more expressive than the C# switch in older versions. Cases are tested in order, so put the most specific first and Case Else last.

C# Stand-in (C#): switch with ranges and lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Testing for Nothing, types and empty text

Reference checks use Is/IsNot, and type checks use TypeOf ... Is:

VB
If customer Is Nothing Then
    Console.WriteLine("No customer")
ElseIf TypeOf customer Is VipCustomer Then
    Console.WriteLine("VIP")
End If

If String.IsNullOrWhiteSpace(name) Then name = "Guest"

VB has no pattern-matching declaration like C#'s x is Dog d: test with TypeOf, then cast with DirectCast or TryCast.

Common mistakes

  • Writing If x = 1 Or 2 expecting "x is 1 or 2". That compares x = 1 or'd with 2. Write x = 1 OrElse x = 2 or Select Case x with Case 1, 2.
  • Comparing floating point values with =. Use a tolerance: Math.Abs(a - b) < 0.0001.
  • Using And/Or where AndAlso/OrElse is needed (null checks fail).
  • Forgetting Case Else, so unexpected input is silently ignored.
  • Ordering ElseIf conditions so an early broad test hides later ones (>= 10 before >= 30).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In an If ... ElseIf ... Else chain, how many branches run?

    VB checks the conditions in order and runs only the first one that is true (or Else).
  2. 2. What does Case 6 To 8 match?

    Ranges in Case are inclusive at both ends.
  3. 3. Is there fall-through between Case branches in Select Case?

    Select Case runs one matching branch and then continues after End Select.
  4. 4. Which condition correctly tests that x is 1 or 2?

    Each comparison must be written out; 'x = 1 Or 2' means something else entirely.

Summary

  • If ... Then ... ElseIf ... Else ... End If runs the first true branch; use the block form for clarity.
  • Combine conditions with AndAlso, OrElse, Not; use guard clauses to avoid deep nesting.
  • If(cond, a, b) picks a value; avoid IIf.
  • Select Case supports values, lists, To ranges and Is comparisons, with no fall-through; add Case Else.
  • Test references with Is Nothing, and watch for the Or 2 trap.

Next: Loops