O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

OPTION EXPLICIT AND OPTION STRICT

The Option Explicit and Option Strict compiler options play an important role in variable declarations.

When Option Explicit is set to on, you must declare all variables before you use them. If Option Explicit is off, Visual Basic automatically creates a new variable whenever it sees a variable that it has not yet encountered. For example, the following code doesn’t explicitly declare any variables. As it executes the code, Visual Basic sees the first statement, num_managers = 0. It doesn’t recognize the variable num_managers, so it creates it. Similarly, it creates the variable i when it sees it in the For loop.

Option Explicit Off
Option Strict Off
 
Public Class Form1
    ...
    Public Sub CountManagers()
        num_managers = 0
        For i = 0 To m_Employees.GetUpperBound(0)
            If m_Employees(i).IsManager Then num_managrs += 1
        Next i
 
        MessageBox.Show(num_managers)
    End Sub
    ...
End Class

Keeping Option Explicit turned off can lead to two very bad problems. First, it silently hides typographical errors. If you look closely at the preceding code, you’ll see that the statement inside the For loop increments the misspelled variable num_managrs instead of the correctly spelled variable num_managers. Because Option Explicit is off, Visual Basic assumes that you want to use a new variable, so it creates num_managrs. After the loop finishes, the program displays the value of num_managers, which is zero because it was never incremented.

The second problem that occurs when Option ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required