Option Explicit Statement


Option Explicit Statement

Syntax

     Option Explicit [On | Off] 

Description

Use the Option Explicit statement to generate a compile-time error whenever a variable that has not been declared is used in a source code file.

Usage at a Glance

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

  • The Option Explicit statement must appear in the declarations section of a source code file, before any types.

  • In source code files where the Option Explicit statement is not used, any undeclared variables are automatically cast as Object.

  • The default action of Option Explicit is On, so that:

         Option Explicit 

    is equivalent to:

         Option Explicit On 

  • It is considered good programming practice to always enable Option Explicit. The following example shows why.

         1:    Dim variable As Integer     2:    variable = 100     3:    variable = varable + 50     4:    MsgBox variable 

    In this code snippet, an integer variable, variable, has been declared. However, because the name of the variable has been mistyped on line 3, the message box shows its value as only 100 instead of 150. This is because varable is assumed to be an undeclared variable with an initial value of 0. If the Option Explicit On statement had been used, the code would not have compiled, and varable would have been highlighted as the cause.

  • For an ASP.NET page, use the @PAGE directive, rather than Option Explicit, to require variable declaration. Its syntax is:

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

    By default, Explicit is true in ASP.NET pages.

    You can also use the <system.web> section of the web.config file to require variable declaration for an entire virtual directory or an ASP.NET application by adding an explicit attribute to the compilation tag. Its syntax is:

         <compilation explicit="true|false"> 

    In both cases, TRue corresponds to Option Explicit On, and false corresponds to Option Explicit Off.

See Also

Option Compare Statement, Option Strict 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