Compartilhar via


Declaração explícita e implícita (Visual Basic)

By default, the Visual Basic compiler enforces explicit declaration, which requires that you declare every variable before you use it. You can remove this requirement and permit implicit declaration.

Visual Basic provides a switch that controls explicit declaration. By default, this switch is set to On, and the compiler enforces explicit declaration. If you turn this switch Off, you can use variables without declaring them.

Explicit Declaration Switch. Você pode definir a opção explícita declaração On ou Off em qualquer uma das seguintes maneiras:

  • Set the appropriate project property in the integrated development environment (IDE). Click <ProjectName> Properties from the Project menu, and then click the Compile tab. You can set the default values for Option explicit, Option strict, and Option compare.

  • Specify the /optionexplicit command-line compiler option.

  • Include the Instrução Option Explicit (Visual Basic) at the beginning of your code.

Se você usar o Option Explicitdedemonstrativo, essa configuração substitui tanto aspropriedade e a opção do compilador configurações do projeto, mas apenas para o arquivo de código fonte em que ele apareça.

Performance Advantage. Definindo Option Explicit para On tem a vantagem de forçar a inferência de tipo a ser feita em tempo de compilar em vez de tempo de execução. This improves performance.

Implicit Declaration

Se você definir Option Explicit para Off, implicitamente, você pode declarar uma variável ao simplesmente usá-lo em seu código. The compiler assigns the Tipo de dados Object to all implicitly declared variables. However, your application is more efficient if you declare all your variables explicitly and with a specific data type. This reduces the incidence of naming-conflict errors and spelling mistakes. It also lets the compiler detect potential run-time errors such as assigning an Integer to a Short.

Potential Errors

Unintended New Variables

You can write a procedure in which you do not declare a local variable. The following example illustrates this.

Function safeSqrt(num)
' Make sure num is positive for square root.
    tempVal = Math.Abs(num)
    Return Math.Sqrt(tempVal)
End Function

Visual Basic automatically creates tempVal as a local variable, which you can use as if you had declared it explicitly. While this is convenient, it can lead to subtle errors in your code if you misspell a variable name. Suppose you had written the procedure in the preceding example as follows:

Function safeSqrt(num)
' Make sure num is positive for square root.
    tempVal = Math.Abs(num)
    Return Math.Sqrt(temVal)
End Function

At first glance, this code looks the same. But because the tempVal variable is misspelled as the argument to Sqrt, the compiler creates an additional local variable called temVal, which is never assigned a value, and your function always returns zero.

Unintended Existing Element Reference

When Visual Basic encounters a new name, it cannot determine whether you meant to declare a new variable implicitly, or whether you misspelled an existing variable name. Therefore it attempts to create a new variable with that name. There might be a variable or other programming element already defined with that name, and your code would use that definition unintentionally.

You can avoid problems with misnamed variables by using explicit declaration.

Explicit Declaration

Had explicit declaration been in effect for the source file containing the safeSqrt procedure in the preceding example, Visual Basic would have recognized tempVal and temVal as undeclared variables and generated errors for both of them. As a result, you would then explicitly declare tempVal. The following example illustrates this.

Function safeSqrt(ByVal num As Double) As Double
' Make sure num is positive for square root.
    Dim tempVal As Double = Math.Abs(num)
    Return Math.Sqrt(temVal)
End Function

With this revised code, you would understand the problem immediately because Visual Basic would display an error message for the incorrectly spelled temVal. Because explicit declaration helps you catch these kinds of errors, it is recommended that you use it with all your code.

ObservaçãoObservação

O Option Explicitdedemonstrativo opera em um arquivo de-pela base do arquivo de-. It must be at the beginning of every source code file in which you want to control the enforcement of explicit variable declaration.

Consulte também

Tarefas

Como: Modificar propriedades do projeto e definições de configuração

Referência

Resumo de tipo de dados (Visual Basic)

Funções de conversão de tipo (Visual Basic)

Conceitos

Programação Sem-Tipos no Visual Basic

Verificação de Tipo no Visual Basic

Objeto como o tipo de dados Universal (Visual Basic)

Uso eficiente de tipos de dados (Visual Basic)

Variáveis no Visual Basic

Convenções de nomeação do Visual Basic