Option Strict Statement


Option Strict Statement

Syntax

     Option Strict [On | Off] 

Description

Use the Option Strict statement to allow or prevent VB from making any implicit data type conversions that are narrowing in a source code file. Option Strict On disallows all implicit narrowing conversions, while the Off setting permits them. Narrowing conversions may involve data loss. For example:

     Dim bigNumber As Long = 2455622     Dim smallNumber As Integer = bigNumber 

converts a Long to an Integer. Even though in this case, no data loss would result from the narrowing, Option Strict On still does not allow the conversion and would instead generate a compiler error.

Usage at a Glance

  • A default project-wide setting for Option Strict can be set in the project properties within Visual Studio. The Option Strict statement, when used in a source code file, takes precedence over the project-wide setting.

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

  • The default action for Option Strict is On, so that:

         Option Strict 

    is equivalent to the statement:

         Option Strict On 

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

  • Option Strict On implies Option Explicit On.

  • Explicit narrowing conversions, such as those using the CInt function, are not affected by Option Strict. However, if data loss does occur as a result of an explicit conversion, a runtime error may still occur.

  • When Option Strict is On, literals must often be cast to a specific data type before use. For example, the statement:

         Dim someMoney As Decimal = 10.32 

    generates a compiler error because 10.32 is interpreted as a Double, and implicit conversions from Double to Decimal are not allowed. You can correct this compiler error with a statement like:

         Dim someMoney As Decimal = 10.32D 

  • Setting Option Strict On is highly recommended.

  • For an ASP.NET page, use the @Page directive, rather than Option Strict, to control strict type checking. Its syntax is:

         <%@ Page Language="VB" Strict=true|false %> 

    By default, Strict is false in ASP.NET pages.

    You can also use the <system.web> section of the web.config file to control strict type checking for an entire virtual directory or an ASP.NET application by adding a strict attribute to the compilation tag. Its syntax is:

         <compilation strict="true|false"> 

    In both cases, true corresponds to Option Strict On, and false corresponds to Option Strict Off.

Version Differences

The Option Strict statement did not exist in VB 6.

See Also

Option Compare Statement, Option Explicit Statement




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net