Visual Basic.NET generally allows implicitconversions of any data type to any other data type. Data loss canoccur when the value of one data type is converted to a data typewith less precision or smaller capacity, however, a run-time errormessage will occur if data will be lost in such a conversion.Option Strict ensures compile-time notification of thesetypes of conversions so they may be avoided.
In addition to disallowing narrowing conversions, OptionStrict generates an error for late binding. An object islate bound when it is assigned to a variable that is declared to beof type Object.
NoteThecompiler default is Option Strict Off if do not specifyOption Strict in your code.Example
This example demonstrates how the Option Strictstatement disallows late binding and conversions where data wouldbe lost.
Option Strict On ' Force explicit variable declaration.Dim MyVar As Integer ' Declare variables.Dim Obj As ObjectMyVar = 1000 ' Declared variable does not generate error.'Attempting to convert to an Integer generates an error.MyVar = 1234567890.987654321''Call Obj.Method1() ' Late-bound call generates an error
Option Explicit OnRemarks
If used, the Option Explicit statement must appear in a file before any other source statements.
When Option Explicit appears in a file, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.
If you don't use the Option Explicit statement, all undeclared variables are of Object type.NoteUseOption Explicit to avoid incorrectly typing the name of anexisting variable or to avoid confusion in code where the scope ofthe variable is not clear. If you do not specify OptionExplicit in your code, the compiler default is OptionExplicit On.Example
This example uses the Option Explicit statement to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time. The Option Explicit statement is used at the module level only.Option Explicit
On ' Force explicit variable declaration.Dim MyVar As Integer ' Declare variable.MyInt = 10 ' Undeclared variable generates error.MyVar = 10 ' Declared variable does not generate error.