SUMMARY

Two of the most important things you control with a variable declaration are its data type and its visibility. Visibility combines scope (the piece of code that contains the variable such as a For loop, subroutine, or module), accessibility (the code that is allowed to access the variable determined by keywords such as Private, Public, and Friend), and lifetime (when the variable has been created and not yet destroyed).

To avoid confusion, explicitly declare the data type whenever possible and use the most limited scope possible for the variable’s purpose. Turn Option Explicit and Option Strict on to allow the IDE to help you spot potential scope and type errors before they become a problem.

Code that uses LINQ complicates matters somewhat. When you use LINQ, it is generally not possible to explicitly declare every variable’s data type. A LINQ query can return a sequence of objects that have an anonymous type. If you enumerate over the sequence, the looping variable will be of the same anonymous type. In those cases, when you cannot explicitly declare a variable’s type, use extra caution to make the code easy to understand so you can fix and maintain it later. For more information on LINQ, see Chapter 20.

Parameters, property procedures, and constants have similar data type and scope issues. Once you become comfortable with variable declarations, they should give you little trouble.

One of the most important steps you can take to make your code easier to debug and maintain ...

Get Visual Basic 2012 Programmer's Reference 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.