Problem: Evil Type Coercion                                                                
VB 6.0 automatically converts between various types of data. This was done for performance and convenience
reasons. However, it can cause some unexpected errors that occur at runtime, rather than at compile time. In the
following code, VB type coercion is a convenient feature. Without it, you would have to explicitly convert the
text value to an integer.

   'VB 6.0 Code
   Dim iNum As Integer
   iNum = txtAge.Text

This type conversion “feature” can hide real programming errors until runtime. Consider the following calls to a
method named EvilTest():

   'More VB 6.0 Code
   Sub SomeMethod()
     Dim sString As String, iNumber As Integer
     sString = "1"
     iNumber = 2

     ' The sub call accidentally reverses the parameters.  
     ' Ok this time...
     EvilTest sString, iNumber

     ' But you will get a runtime error here!  
     ' A compile error would be preferred.
     sString = "Not OK this time!"
     EvilTest sString, iNumber
   End Sub

   Sub EvilTest(ByVal iNum As Integer, ByVal sName As String)
     
 'Do something...
   End Sub

VB supports the Option Strict statement to force explicit type conversion. Any attempt to assign variables that
are not the same type causes a compiler error. This is true, even if the values can be easily converted. Consider
the following:

   'VB Code
   Option Strict On

   Public Class TestClass
      Sub SomeMethod()
      Dim aString As String
      Dim aNumber As Integer
      aString = "1"
      aNumber = 2

     ' Both of these calls result in a compile error.  
      EvilTest(aString, aNumber)
      aString = "Some string value"
      EvilTest(aString, aNumber)
      End Sub

     Sub EvilTest(num As Integer, name As String)
      'Do something
     End Sub
   End Class

You can (and should) enable Option Strict on a project-wide level. To do so, double-click on the My Project
icon within the Solution Explorer of Visual Studio.  Once you have done so, click on the Compile tab and enable
Option Strict.
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Data
Table of Contents
Courseware
Training Resources
Tutorials