A form, class, or code module should contain the following sections in this order (if they are present — you can omit some):

  • Option statements — Option Explicit, Option Strict, Option Compare, or Option Infer. By default, Option Explicit is on, Option Strict is off, Option Compare is binary, and Option Infer is on.
  • Imports statements — These declare namespaces that the module will use.
  • A Main subroutine — The routine that starts execution when the program runs.
  • Class, Module, and Namespace statements — As needed.
To uncover potentially annoying and sometimes elusive bugs, turn Option Explicit on, Option Strict on, and Option Infer off. The section “Project” in Chapter 2 describes these options.

Some of these items may be missing. For example, Option and Imports statements are optional. Note that an executable Windows program can start from a Main subroutine or it can start by displaying a form, in which case it doesn’t need a Main subroutine. (In that case, the program starts with the automatically generated New subroutine in the file Application.Designer.vb.) Classes and code modules don’t need Main subroutines.

The following code shows a simple code module. It sets Option Explicit On (so variables must be declared before used), Option Strict On (so implicit type conversions cause an error), and Option Infer Off (so you must give variables explicit data types). It imports the System.IO namespace so the program can easily use the ...

Get Visual Basic 2012 Programmer's Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.