Variables are among the most fundamental building blocks of a program. A variable is a program object that stores a value. The value can be a number, letter, string, date, structure containing other values, or an object representing both data and related actions.
When a variable contains a value, the program can manipulate it. It can perform arithmetic operations on numbers, string operations on strings (concatenation, calculating substrings, finding a target within a string), date operations (find the difference between two dates, add a time period to a date), and so forth.
Four factors determine a variable’s exact behavior:
For example, a variable declared within a subroutine has scope equal to the subroutine. Code outside of the subroutine cannot access the variable. If a variable is declared on a module level outside any subroutine, it has module scope. If it is declared with the Private keyword, it is accessible only to code within the module. If it is declared with the Public keyword, then it is also accessible to code outside of the module.
Visibility is a concept that combines scope, accessibility, and lifetime. It determines whether a certain piece of code can use a variable. If the variable is accessible to the code, the code is within the variable’s scope, and the variable is within its lifetime (has been created and not yet destroyed), then the variable is visible to the code.
This chapter explains the syntax for declaring variables in Visual Basic. It explains how you can use different declarations to determine a variable’s data type, scope, accessibility, and lifetime. It discusses some of the issues you should consider when selecting a type of declaration, and describes some concepts, such as anonymous and nullable types, which can complicate variable declarations. This chapter also explains ways you can initialize objects, arrays, and collections quickly and easily.
Constants, parameters, and property procedures all have concepts of scope and data type that are similar to those of variables, so they are also described here.
The chapter finishes with a brief explanation of naming conventions. Which naming rules you adopt isn’t as important as the fact that you adopt some. This chapter discusses where you can find the conventions used by Microsoft Consulting Services. From those, you can build your own coding conventions.