Total .NET Analyzer Rule Documentation  

OptionExplicitNotSet Rule

Set Option Explicit for all projects.

Remarks

Although Visual Basic .NET allows you to use variables without declaring them, it is a very unwise practice. Using undeclared variables has several key problems, including:

1. If a variable is not declared, the Visual Basic compiler will guess at its type based on the data that is put into it. Often, this guess causes inefficient type use. Additionally, the Visual Basic compiler has to generate a great deal of handling code to cast variables from one data type to another. This can lead to poor performance, increased program size, and unexpected results.

2. Use of non-declared variables eliminates almost all the benefits of the .NET common type system, which enables cross-language integration, type safety, and high performance code execution.

3. Non-declared variables make code very difficult to understand and debug. For large, complex applications, non-declared variables can result in program code that is indecipherable.

4. Use of non-declared variables makes it easy to inadvertently declare a new variable by mistyping the name of an existing variable.

Resolution

You should turn Option Explicit on for all files in a project by following these steps:

1. With a project selected in Solution Explorer, choose View, Property Pages from the menu.
2. When the Property Page appears, highlight "Build" (under Common Properties on the left).
3. Under Compiler Defaults, set Option Explicit to "On."

This sets the default to Option Explicit On. Note that you can manually override this default for individual files by adding the "Option Explicit Off" statement to individual files.

Note: The best coding practice in Visual Basic .NET is to use strict typing by specifying the Option Strict statement. Having Option Strict on disallows implicit type conversions, which can cause run time errors. If you set Option Strict On, the compiler automatically assumes the Option Explicit On statement.

See Also

Option Explicit Statement

Total .NET Analyzer Option Strict Rule