Name

Option Strict Statement

Syntax

Option Strict [On | Off]

Description

Option Strict prevents VB from making any implicit data type conversions that are narrowing since narrowing conversions may involve data loss. For example:

Dim lNum As Long = 2455622
Dim iNum As Integer = lNum

converts a Long (whose value can range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) to an Integer (whose value can range from 2,147,483,648 to 2,147,483,647). In this case, even though no data loss would result from the narrowing, Option Strict On would still not allow the conversion and would instead generate a compiler error. The reasoning here is that, although particular narrowing operations may not lose data, there is always the potential for data loss when working with variables—that is, with symbolic representations of numbers whose values are allowed to vary.

Rules at a Glance

  • If the Option Strict statement is not present in a module, Option Strict is Off.

  • The default is Option Strict On. In other words, the statement:

    Option Strict On

    is equivalent to the statement:

    Option Strict
  • The Option Strict statement must appear in the declarations section of a module before any code.

  • Option Strict On disallows all implicit narrowing conversions.

  • Option Strict On also causes errors to be generated for late binding, as well as for any undeclared variables, since Option Strict On implies Option Explicit On.

Programming Tips and Gotchas

  • Although the setting of Option Strict has no effect on BCL ...

Get VB .NET Language in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.