- Introduction
- Magic Squares
- Initializing the Control Array
- Define Versus Declare
- Using the Control Array
- Conclusion
One of my pet crusades is to clarify the confusion that results from improper use of define and declare as those terms pertain to programming. Too often, programmers use these two terms as though they have the same meaning. They don't, and I'm going to keep harping on this until everyone on the planet gets it right. To illustrate my point, after you've typed in the code, set a breakpoint on the For loop in Listing 2. Now, run the program to the breakpoint and then examine txtElement in the Autos debug window. If you haven't passed through the loop yet, txtElement(0) will be set to Nothing.
What does this mean?
The fact that txtElement(0) is Nothing means the Windows Memory Manager (WMM) has not yet allocated memory for the txtElement(0) object. Clearly, the statement:
Private txtElement(MAXELEMENTS) As TextBox
didn't allocate any memory for the array elements. Therefore, the statement for the txtElement() array in Listing 1 is a data declaration. Now single-step the program past the first statement in the statement body of the For loop. You'll see the entry of txtElement(1) in the Autos window change to this:
+ (1) {System.Windows.Forms.TextBox} System.Windows.Forms.TextBox
This means that the WMM has allocated enough memory to hold one text box object in memory and tied that memory to txtElement(1).
NOTE
Element 1 is defined on the first pass through the loop because the algorithm is easier to understand if we use a 1-based rather than a 0-based array.
Because memory has been allocated for the text box, we can say that txtElement (1) is defined. In compiler jargon, txtElement (1) has an lvalue (location value) where the object resides in memory.
TIP
For additional details, see my InformIT article "Do You Really Understand Parameter Passing in Visual Basic.NET?"
Other languages, such as C and C++, make a clearer distinction between define and declare. If you're familiar with those languages, you know that function prototypes don't allocate memory, while function bodies do. Therefore, function prototypes declare the function (no memory allocated), and the actual function body defines the function (memory is allocated).
Keep in mind that the VBN keyword New is associated with the definition of a data object, and Dim (or a VBN storage specifier such as Private or Public) defines native datatypes.
CAUTION
An exception to the Dim rule: Dynamic arrays in which a reference pointer is actually defined. But that's another story.
The key distinction is that data declarations do not allocate memory, and data definitions do allocate memory. Truly understanding the difference between define and declare will help you to better understand the data in your program and, hence, help you to debug your code more quickly.