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 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 open, Visual Basic creates undeclared variables as generic Objects. Then it can fill the variable with just about anything. Unfortunately, this can make the code much less efficient than it needs to be. For example, programs are much better at manipulating integers than they are at manipulating objects. If you are going to use a variable as an integer, creating it as an object makes the program run much slower.


IMPRECISE INFERENCE
If Option Infer is on, Visual Basic may be able to deduce an explicit data type for a variable declared without a type. In that case, the program may not incur a performance penalty. It won’t be clear from the code whether that’s the case, however, so it could lead to some confusion.
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 performs an operation called boxing, where it wraps the value in an object so it can use references to the boxed value. If you then perform an operation involving two boxed values, Visual Basic must unbox them, perform the operation, and then possibly box the result to store it in another reference variable. All of this boxing and unboxing has a significant overhead.

Example program TimeGenericObjects, which is available for download on the book’s website, uses the following code to demonstrate the difference in speed between using variables with explicit types and using variables of the generic Object type:

Dim num_trials As Integer = Integer.Parse(txtNumTrials.Text)
 
Dim start_time As DateTime
Dim stop_time As DateTime
Dim elapsed_time As TimeSpan
 
start_time = Now
For i As Integer = 1 To num_trials
 
Next i
stop_time = Now
elapsed_time = stop_time.Subtract(start_time)
lblIntegers.Text = elapsed_time.TotalSeconds.ToString("0.000000")
Refresh()
 
start_time = Now
For j = 1 To num_trials
 
Next j
stop_time = Now
elapsed_time = stop_time.Subtract(start_time)
lblObjects.Text = elapsed_time.TotalSeconds.ToString("0.000000")

The code executes two For loops. In the first loop, it explicitly declares its looping variable to be of type Integer. In the second loop, the code doesn’t declare its looping variable (an easy typo to make), so Visual Basic automatically makes it an Object when it is needed. In one test, the second loop took more than 60 times as long as the first loop.

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 necessarily 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 run time.

Dim i As Integer
Dim s As String
s = "10"
i = s       ' This works.
s = "Hello"
i = s       ' This Fails.

If you turn Option Strict on, Visual Basic warns you of possibly illegal conversions at compile time. You can still use conversion functions such as CInt, Int, and Integer.Parse to convert a string into an Integer, but you must take explicit action to do so.

To avoid confusion and ensure total control of your variable declarations, you should always turn on Option Explicit and Option Strict.

For more information on Option Explicit and Option Strict (including instructions for turning these options on), see the “Project” section in Chapter 2, “Menus, Toolbars, and Windows.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.93.137