Recipe 3.3. Creating a Structure


Problem

You would like to add a new structure to your Visual Basic application.

Solution

Visual Studio does not include an Add Structure menu command, or even a structure-focused template available via the Project Add New Item menu command. If you want to include a structure in a file all its own, use the Project Add New Item menu command, and select the Code File template in the Add New Item dialog, as shown in Figure 3-3. You can also simply type a new structure construct in any existing source-code file.

Figure 3-3. Adding a new structure in Visual Studio


Discussion

The syntax for a structure is very similar to that of a class:

 Structure Structure1 End Structure 

Add members to your structure just as you would in a class. Since structures cannot be used to derive other structures, some keywords that support derived classes (such as the Protected and MustOverride keywords) cannot be used.

Structures must have at least one public instance member or event definition.

The .NET Framework defines two categories of types: reference types and value types. Value types contain basic data at the memory location assigned for a specific instance. If you looked at the memory location assigned to an Integer value type instance, you would find the Integer value that the program last assigned to that variable.

Reference types store their data indirectly. The memory location assigned to a reference type contains another memory address that identifies the true storage area of the data. (This is similar to the pointer used in programming languages such as C.)

In Visual Basic, classes define reference types, while structures define value types. All classes and structures ultimately derive from the common System.Object class, but value types go through the related System.ValueType class on the way to System.Object.

Because structures store their data directly, they are sometimes faster to use (by the CPU) than classes, and their data can be stored on the application stack. Classes always require one or more trips to main memory. However, structures do have some limitations not placed on classes. Structures cannot be used as bases for other structures, nor can a structure derive from other structures or classes. Also, structures do not support destructors, which are special methods included in classes that perform final cleanup of resources whenever a class instance is being destroyed.

See Also

Recipes 3.1 and 3.2 introduce modules and classes, the two other major type constructs in Visual Basic.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net