Skip to content
LumenaryAcademy
Foundations 55 min

Variables, types and control flow

Visual Basic's types and operators, the conversions Option Strict makes you write, and its readable decision and loop statements.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Code that reads like a sentence

Visual Basic was designed to be read aloud. If total > limit AndAlso Not approved Then, For year As Integer = 2026 To 2014 Step -4, Select Case distanceKm ... Case 1 To 10, Do Until n = 1: you can follow these lines without knowing the language. That readability is the main reason so much business software was written in it, and the main reason maintaining it can be pleasant.

But readable is not the same as obvious. Visual Basic has three division operators, two pairs of logical operators that behave differently, arrays declared by their last index, integer overflow that is checked by default, and conversions that round in an unusual way. This lesson covers the everyday language, with special attention to the places where Visual Basic differs from C# and Python, because those are exactly where bugs hide in code that is moved, translated or maintained by someone new. Every program in it starts with Option Strict On, so the compiler insists on the explicit conversions that make such code easy to reason about.

DefinitionsH

Types, values and operators

Visual Basic.NET typeHoldsDefault
BooleanSystem.BooleanTrue or FalseFalse
Byte, Short, Integer, LongByte, Int16, Int32, Int64whole numbers of 8, 16, 32, 64 bits0
Single, DoubleSingle, Doublebinary floating point0
DecimalSystem.Decimalexact base-10 numbers, for money0
CharSystem.Charone UTF-16 charactercharacter 0
StringSystem.StringtextNothing
DateSystem.DateTimea date and time1 January of year 1, midnight
ObjectSystem.ObjectanythingNothing

Literals can carry a suffix: 8_000_000_000L is a Long, 0.16D a Decimal, 2.5F a Single. Older code uses type characters on names instead, such as count% for an Integer or name$ for a String; you will see them in legacy code, but do not write them in new code. Nothing is Visual Basic's word for "no object" (C#'s null), and for value types it means the type's default value. Const declares a value fixed at compile time.

Definition— The division operators

/ always performs floating-point division (7 / 2 is 3.5, even for two integers). \ performs integer division, discarding the remainder (7 \ 2 is 3). Mod gives the remainder, with the sign of the left operand. ^ raises to a power and returns a Double.

vb
Option Strict On

Module Program
    Sub Main()
        ' Three kinds of division, plus remainder and power.
        Console.WriteLine($"7 / 2 = {7 / 2}")        ' always floating point
        Console.WriteLine($"7 \ 2 = {7 \ 2}")        ' integer division
        Console.WriteLine($"7 Mod 2 = {7 Mod 2}, -7 Mod 2 = {-7 Mod 2}")
        Console.WriteLine($"2 ^ 10 = {2 ^ 10}")      ' power, as a Double

        ' Decimal is exact for money; Double is binary floating point.
        Dim d As Double = 0.1 + 0.2
        Dim m As Decimal = 0.1D + 0.2D
        Console.WriteLine($"Double: {d}, Decimal: {m}")

        ' Unlike C#, Visual Basic checks integer overflow by default.
        Dim big As Integer = Integer.MaxValue
        Try
            big += 1
        Catch ex As OverflowException
            Console.WriteLine($"Overflow caught: {ex.Message}")
        End Try

        ' Defaults: numbers start at 0, Boolean at False, strings and objects at Nothing.
        Dim count As Integer
        Dim done As Boolean
        Dim title As String = Nothing
        Console.WriteLine($"{count} {done} {title Is Nothing}")

        ' Constants and type characters.
        Const VatRate As Decimal = 0.16D
        Dim large As Long = 8_000_000_000L
        Console.WriteLine($"{VatRate * 250D} {large:N0}")
    End Sub
End Module

It prints:

text
7 / 2 = 3.5
7 \ 2 = 3
7 Mod 2 = 1, -7 Mod 2 = -1
2 ^ 10 = 1024
Double: 0.30000000000000004, Decimal: 0.3
Overflow caught: Arithmetic operation resulted in an overflow.
0 False True
40.00 8,000,000,000

Three differences from C# deserve emphasis:

  • / never truncates. A C# programmer expects 7 / 2 to be 3; in Visual Basic it is 3.5. Code translated between the languages must change / to \ (or the reverse) wherever integer division was meant.
  • Integer overflow is checked by default. Adding 1 to Integer.MaxValue throws an OverflowException instead of silently wrapping around, which is safer. (A project setting, RemoveIntegerChecks, turns the checks off; you will occasionally find it in performance-tuned code.) Try ... Catch handles the exception; a later lesson covers it fully.
  • Precedence puts \ below * and /, and Mod below \. So 17 \ 5 * 2 means 17 \ (5 * 2), which is 1. When in doubt, add parentheses.

& joins text and + adds numbers. + can also join two strings, but with Option Strict Off it may try to add a string to a number, so always use & for text.

Worked examplesH

Logic, conversions and patterns

Visual Basic has two sets of logical operators, for historical reasons. In classic Visual Basic, And and Or always evaluated both sides (they double as bitwise operators). VB.NET kept them, and added AndAlso and OrElse, which short-circuit: they skip the right side when the left side already decides the answer.

vb
Option Strict On

Module Program
    Function Check(label As String, result As Boolean) As Boolean
        Console.Write($"[{label}] ")
        Return result
    End Function

    Sub Main()
        ' And / Or always evaluate both sides; AndAlso / OrElse stop early.
        Console.WriteLine(Check("a", False) And Check("b", True))
        Console.WriteLine(Check("a", False) AndAlso Check("b", True))
        Console.WriteLine(Check("c", True) OrElse Check("d", True))

        ' AndAlso protects the second test.
        Dim name As String = Nothing
        If name IsNot Nothing AndAlso name.Length > 3 Then
            Console.WriteLine("long name")
        Else
            Console.WriteLine("no name, and no crash")
        End If

        ' If() is the conditional operator: only the chosen branch is evaluated.
        Dim stock As Integer = 0
        Console.WriteLine(If(stock > 0, "in stock", "sold out"))
        Console.WriteLine(If(name, "(anonymous)"))   ' two arguments: a fallback for Nothing

        ' Explicit conversions.
        Console.WriteLine($"{CInt(2.5)} {CInt(3.5)} {CInt("17")} {CDbl("2.5")} {CStr(42)}")
        Dim parsed As Integer
        If Integer.TryParse("12a", parsed) Then
            Console.WriteLine(parsed)
        Else
            Console.WriteLine("'12a' is not a whole number")
        End If

        ' Like: simple wildcard matching, unique to Visual Basic.
        For Each code In {"AB-1234", "AB-12", "XY-9876"}
            Console.WriteLine($"{code}: {code Like "AB-####"}")
        Next
    End Sub
End Module

It prints:

text
[a] [b] False
[a] False
[c] True
no name, and no crash
sold out
(anonymous)
2 4 17 2.5 42
'12a' is not a whole number
AB-1234: True
AB-12: False
XY-9876: False
  • Always use AndAlso and OrElse for conditions. And evaluated Check("b", ...) even though the left side was already False. With name IsNot Nothing And name.Length > 3, that would crash on a missing name; AndAlso protects the second test. Keep And, Or and Xor for bitwise work on numbers. In old code, replacing And with AndAlso is usually a good change, but check that the right-hand side has no side effect that something relies on.
  • Not negates a Boolean, and <> means "is not equal to"; a single = is both assignment and comparison, decided by context.
  • Is and IsNot compare object references, and are how you test for Nothing: x Is Nothing, x IsNot Nothing. (= compares values; using it with Nothing on a reference type is a common mistake.)
  • If(condition, a, b) is the conditional operator, evaluating only the chosen branch; with two arguments, If(x, fallback) returns x unless it is Nothing. Do not confuse it with the old function IIf, which always evaluates both branches and returns Object.
  • Conversion functions CInt, CLng, CDbl, CDec, CStr, CBool, CDate convert explicitly. Note that CInt rounds halves to the even number (2.5 becomes 2, 3.5 becomes 4), unlike C#'s cast, which truncates. Converting from text with CInt or CDbl uses the computer's current culture, so "2,5" might be two and a half in one country and twenty-five in another; for text from files and networks, use Integer.TryParse or Double.Parse with an explicit culture. CType(x, T) converts to any type, and DirectCast and TryCast convert between reference types.
  • Like matches a string against a simple pattern: # is any digit, ? any single character, * any run of characters, and [A-Z] a range. It is handy for validating codes and identifiers; for anything more complex, use regular expressions (System.Text.RegularExpressions).
Worked examplesH

Working with text

Strings in Visual Basic are .NET strings, so every member of System.String is available. Older code also uses the functions of the Microsoft.VisualBasic library, which Visual Basic projects import automatically. Both work; the trap is that they count differently.

vb
Option Strict On

Imports System.Text

Module Program
    Sub Main()
        Dim city As String = "Valparaíso"

        ' .NET string members count from 0...
        Console.WriteLine($"{city.Length} {city.Substring(0, 4)} {city.IndexOf("par")} {city.ToUpper()}")
        ' ...the older Microsoft.VisualBasic functions count from 1.
        Console.WriteLine($"{Len(city)} {Left(city, 4)} {InStr(city, "par")} {Mid(city, 4, 3)}")

        ' Comparisons are case-sensitive by default (Option Compare Binary).
        Console.WriteLine($"{"apple" = "Apple"} {String.Equals("apple", "Apple", StringComparison.OrdinalIgnoreCase)}")

        ' Strings are immutable; build long ones with a StringBuilder.
        Dim sb As New StringBuilder()
        For i As Integer = 1 To 5
            sb.Append(i).Append(If(i < 5, ", ", "."))
        Next
        Console.WriteLine(sb.ToString())

        ' Since Visual Basic 14, string literals may span several lines.
        Dim note As String = "Line one
Line two"
        Console.WriteLine(note.Split(ControlChars.Lf).Length & " lines")

        ' A quote inside a string is written twice.
        Console.WriteLine("She said ""hello"".")
    End Sub
End Module

It prints:

text
10 Valp 3 VALPARAÍSO
10 Valp 4 par
False True
1, 2, 3, 4, 5.
2 lines
She said "hello".
  • Zero-based and one-based. city.IndexOf("par") is 3 (counting from 0), while InStr(city, "par") is 4 (counting from 1), and Mid(city, 4, 3) starts at the fourth character. Mixing the two families in one expression is a classic maintenance bug. In new code, prefer the .NET members, which are the same in C# and F#.
  • Comparisons with = are case-sensitive by default. A file can declare Option Compare Text to make =, <, Like and InStr case-insensitive; you will find it in older code, and it can surprise people who do not notice the line at the top. Explicit comparisons, String.Equals(a, b, StringComparison.OrdinalIgnoreCase), say what they mean wherever they appear.
  • Building strings. Strings never change; each & creates a new one. For a loop that builds a long string, use a StringBuilder, whose Append returns the builder itself, so calls can be chained.
  • Literals. A double quote inside a string is written as two double quotes. Since Visual Basic 14 (2015), a string literal can span several lines; older code joins lines with vbCrLf or Environment.NewLine.
Worked examplesH

Decisions, loops and arrays

Visual Basic's control statements are all closed by a keyword (End If, End Select, Next, Loop, End While), so they read clearly even when nested.

vb
Option Strict On

Module Program
    Function Zone(distanceKm As Integer) As String
        ' Select Case accepts single values, lists, ranges and comparisons.
        Select Case distanceKm
            Case 0
                Return "same street"
            Case 1 To 10
                Return "local"
            Case 11 To 100, 150
                Return "regional"
            Case Is > 1000
                Return "international"
            Case Else
                Return "national"
        End Select
    End Function

    Sub Main()
        For Each km In {0, 7, 64, 150, 420, 5000}
            Console.WriteLine($"{km,5} km: {Zone(km)}")
        Next

        ' For...Next with Step; the loop variable can be declared inline.
        For year As Integer = 2026 To 2014 Step -4
            Console.Write($"{year} ")
        Next
        Console.WriteLine()

        ' Do...Loop with Until, Exit and Continue.
        Dim n As Integer = 27
        Dim steps As Integer = 0
        Do Until n = 1
            n = If(n Mod 2 = 0, n \ 2, 3 * n + 1)
            steps += 1
        Loop
        Console.WriteLine($"Collatz steps from 27: {steps}")

        For i As Integer = 1 To 20
            If i Mod 3 <> 0 Then Continue For
            If i > 12 Then Exit For
            Console.Write($"{i} ")
        Next
        Console.WriteLine()

        ' Arrays are declared by their UPPER BOUND, not their length.
        Dim scores(4) As Integer
        Console.WriteLine($"Dim scores(4) has {scores.Length} elements, indexes 0 to {scores.GetUpperBound(0)}")
        Dim days() As String = {"Mon", "Tue", "Wed"}
        Console.WriteLine($"{days(0)} ... {days(days.Length - 1)}")
    End Sub
End Module

It prints:

text
    0 km: same street
    7 km: local
   64 km: regional
  150 km: regional
  420 km: national
 5000 km: international
2026 2022 2018 2014 
Collatz steps from 27: 111
3 6 9 12 
Dim scores(4) has 5 elements, indexes 0 to 4
Mon ... Wed
  • Select Case is more flexible than C#'s classic switch: a Case can list several values, a range (1 To 10), or a comparison (Is > 1000), and the first matching case wins. Case Else catches everything else. There is no fall-through between cases, and no break to forget.
  • For ... To ... Step counts in either direction; the loop variable can be declared in the For itself. For Each walks any collection. The array literal {0, 7, 64} creates an array in place.
  • Do ... Loop has four forms: Do While cond, Do Until cond (test first), and Loop While cond, Loop Until cond (test last, so the body runs at least once). While ... End While also exists.
  • Exit For, Exit Do, Exit Sub leave a loop or a procedure; Continue For and Continue Do skip to the next pass. A single-line If ... Then statement needs no End If.

With blocks

One more statement is worth knowing because it is everywhere in Windows Forms code. With lets you refer to one object's members repeatedly without naming it each time; inside the block, a member name that starts with a dot belongs to that object:

vb
With orderGrid
    .ReadOnly = True
    .AllowUserToAddRows = False
    .Columns(0).HeaderText = "Order"
End With

It is purely a convenience; keep With blocks short, because a reader must remember which object the dots refer to.

The array trap

Dim scores(4) As Integer creates an array with five elements, indexed 0 to 4. The number in a Visual Basic array declaration is the upper bound, not the length. This dates from classic Visual Basic and is the source of countless off-by-one mistakes, especially when code is translated to or from C#, where new int[4] has four elements. When you can, avoid the question: create arrays from literals ({"Mon", "Tue", "Wed"}), use List(Of T) (the next lessons), and loop with For Each or up to array.Length - 1. Array elements are accessed with parentheses, days(0), the same syntax as a procedure call.

ExplanationH

Reading older Visual Basic code

Maintenance work means reading code written in older styles. Some things you will meet, and what to do about them:

  • Functions from Microsoft.VisualBasic, such as Len(s), Left(s, 3), Mid(s, 2, 4), InStr, UCase, Format, CStr(Now). They still work and are fully supported. Note that Mid and InStr count from 1, while .NET's Substring and IndexOf count from 0, a frequent source of bugs when mixing the two. Converting to .NET methods (s.Length, s.Substring(0, 3), s.ToUpper()) helps future readers, especially if the code may move to C#.
  • Type characters and implicit types: Dim total%, Dim name$, or variables declared without As under Option Strict Off, which become Object.
  • IIf instead of If(): it evaluates both branches, so IIf(x Is Nothing, 0, x.Length) crashes when x is Nothing.
  • And and Or in conditions: fine when both sides are simple, dangerous when the right side depends on the left.
  • GoTo and line labels: legal, occasionally found in very old code, and nearly always replaceable with structured loops.

Change such code in small, tested steps. Old programs often depend on their quirks in ways that are not obvious until something breaks.

Common misconceptionsH

Common misconceptions

Misconception

"7 / 2 is 3, as in C# and Java." In Visual Basic, / always divides as floating point, giving 3.5. Use \ for integer division. Getting this wrong when translating code between languages changes results silently.

Misconception

"And and AndAlso are interchangeable." And always evaluates both operands, so a guard such as x IsNot Nothing And x.Count > 0 still throws when x is Nothing. AndAlso stops after the first operand if it is False.

Misconception

"Dim a(10) As Integer makes ten elements." It makes eleven, indexed 0 to 10, because the number is the upper bound. Prefer array literals, List(Of T) and For Each, which avoid the question.

Exercises

Exercises

1. Variables, types and control flow

StretchComputational

What does this line print (with Option Strict On)?

Console.WriteLine(17 \ 5 * 2 + 17 Mod 5)

2. Variables, types and control flow

Warm-upComputational

What does this print?

Dim arr(3) As String
Console.WriteLine(arr.Length)

3. Variables, types and control flow

CoreComputational

What does Console.WriteLine(CInt(0.5) + CInt(1.5) + CInt(2.5)) print?

4. Variables, types and control flow

CoreComputational

What does this program print?

Option Strict On

Module Program
    Dim calls As Integer = 0

    Function Positive(x As Integer) As Boolean
        calls += 1
        Return x > 0
    End Function

    Sub Main()
        Dim a = Positive(-1) And Positive(2)
        Dim b = Positive(-1) AndAlso Positive(2)
        Dim c = Positive(3) OrElse Positive(4)
        Console.WriteLine($"{a} {b} {c} {calls}")
    End Sub
End Module

5. Variables, types and control flow

CoreComputational

What does this print?

Dim total As Integer = 0
For i As Integer = 10 To 1 Step -3
    total += i
Next
Console.WriteLine(total)

6. Variables, types and control flow

CoreComputational

With the default Option Compare Binary, what does this print?

Console.WriteLine($"{"Lagos" Like "L*s"} {"Lima" Like "L?ma"} {"Lima" Like "l*"}")

7. Variables, types and control flow

CoreHuman

For Dim city As String = "Valparaíso", which pairs of expressions give the same result? (Choose all that apply.)

Choose all that apply

Further reading and resources