Skip to content
AgileLogics
4 min read

How Visual Basic Code Runs

Prerequisites: Your first program

Visual Basic is a compiled language:

  1. The VB compiler (vbc, run for you by dotnet build) checks your code and compiles it to IL (Intermediate Language), stored in a .dll file. C# and F# compile to the same IL.
  2. The .NET runtime loads the IL, and its JIT compiler turns it into native machine code as the program runs.

Compile errors

Module Program
    Sub Main()
        Console.WriteLine("start")
        Console.WriteLine(total)
    End Sub
End Module
main.vb(4) : error BC30451: 'total' is not declared. It may be inaccessible due to its protection level.

        Console.WriteLine(total)
                          ~~~~~

Nothing ran — not even "start" — because the program didn't compile. The message gives the line number (4) and an error code (BC30451) you can search for. Visual Studio underlines the problem as you type.

Runtime errors (exceptions)

Module Program
    Sub Main()
        Console.WriteLine("start")
        Dim numbers() As Integer = {1, 2, 3}
        Console.WriteLine(numbers(5))
    End Sub
End Module
start
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Demo.Program.Main()

This time "start" printed, then reading element 5 of a 3-element array raised an exception that stopped the program. The stack trace (at Demo.Program.Main()) shows where it happened. In a Debug build, it also includes file names and line numbers.

Line continuation

A statement normally fits on one line. Long statements can continue on the next line after an operator, a comma, or an opening parenthesis:

Module Program
    Sub Main()
        Dim message = "This is a long message " &
                      "split over two lines"
        Console.WriteLine(message)
    End Sub
End Module
This is a long message split over two lines

Old code uses an explicit _ (space and underscore) at the end of each continued line; since VB 2010 it's rarely needed.