Restricts implicit data type conversions to only widening conversions. This explicitly disallows any data type conversions in which data loss would occur and any conversion between numeric types and strings.
Option Strict { On | Off }
Parts
- On
- Optional. Enables Option Strict checking. If On or Off is not specified after the Option Strict statement, the default is On.
- Off
- Optional. Disables Option Strict checking.
Remarks
When used, the Option Strict statement must appear before any other code.
Visual Basic .NET generally allows implicit conversions of any data type to any other data type. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity, however, a run-time error message will occur if data will be lost in such a conversion. Option Strict ensures compile-time notification of these types of conversions so they may be avoided.
In addition to disallowing narrowing conversions, Option Strict generates an error for late binding. An object is late bound when it is assigned to a variable that is declared to be of type Object.
Note The compiler default is Option Strict Off if do not specify Option Strict in your code.
Example
This example demonstrates how the Option Strict statement disallows late binding and conversions where data would be lost.
Option Strict On ' Force explicit variable declaration.
Dim MyVar As Integer ' Declare variables.
Dim Obj As Object
MyVar = 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
See Also
Widening and Narrowing Conversions | Option Explicit Statement | Option Compare Statement | /optionexplicit | /optionstrict | /optioncompare:binary | /optioncompare:text