|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Option Strict Statement
Restricts implicit data type conversions to only widening conversions.
If used, the Option Strict statement must appear in a file before any other source code statements.
Visual Basic allows conversions of many data types to other data types. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity. A run-time error occurs if such a narrowing conversion fails. Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided.
In addition to disallowing implicit 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.
Because Option Strict On provides strong typing, prevents unintended type conversions with data loss, disallows late binding, and improves performance, its use is strongly recommended.
The compiler default is Option Strict Off if you do not specify Option Strict in your code.
You can also set Option Strict in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Strict in the integrated development environment (IDE)
On the Tools menu, choose Options.
Open the Projects and Solutions node.
Choose VB Defaults.
Modify the Option Strict setting.
To set Option Strict on the command line
Include thecompiler option in the vbc command.
The following example demonstrates how the Option Strict statement disallows late binding and conversions where data would be lost.
Dim thisVar As Integer Dim thisObj As Object = New widget thisVar = 1000 ' Declared variable does not generate error. ' Attempting to convert Double to Integer generates a COMPILER ERROR. thisVar = 1234567890.9876542 ' causes ERROR ' Late-bound call generates a COMPILER ERROR. Call thisObj.Method1() ' causes ERROR