The Option Explicit and Option Strict compiler options play an important role in variable declarations.
is set to
, you must declare all
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 MsgBox(num_managers) End Sub ... End Class
turned off can lead to two very bad problems. First, it silently hides typographical errors. If you look closely at the previous code, you’ll see that the statement inside the
The second problem that occurs when Option Explicit is off is that Visual Basic doesn’t really know what you will want to do with the variables it creates for you. It doesn’t know whether you will use a variable as an Integer, Double, String, or PictureBox. Even after you assign a value to the variable (say, an Integer), Visual Basic doesn’t know whether you will always use the variable as an Integer or whether you might later want to save a String in it.
To keep its options
In more advanced terms, integers are value types, whereas objects are reference types. A reference type is really a fancy pointer that represents the location of the actual object in memory. When you treat a value type as a reference type, Visual Basic
The following code executes two
Const TRIALS As Integer = 10000000 Dim start_time As DateTime Dim stop_time As DateTime Dim elapsed_time As TimeSpan Dim i As Integer start_time = Now For i = 1 To TRIALS Next i stop_time = Now elapsed_time = stop_time.Subtract(start_time) MsgBox(elapsed_time.TotalSeconds.ToString("0.000000")) start_time = Now For j = 1 To TRIALS Next j stop_time = Now elapsed_time = stop_time.Subtract(start_time) MsgBox(elapsed_time.TotalSeconds.ToString("0.000000"))
The second compiler directive that influences variable declaration is Option Strict . When Option Strict is turned off, Visual Basic silently converts values from one data type to another, even if the types are not very compatible. For example, Visual Basic will allow the following code to try to copy the string s into the integer i . If the value in the string happens to be a number (as in the first case), this works. If the string is not a number (as in the second case), this throws an error at runtime.
Dim i As Integer Dim s As String s = "10" i = s ' This works. s = "Hello" i = s ' This Fails.
To avoid confusion and ensure total control of your variable declarations, you should always turn on
. (Frankly, it’s
For more information on Option Explicit and Option Strict (including instructions for turning these options on), see the “Project” section in Chapter 1.