42
be used within a type definition, however if you want to save the type information to the
disk, then you need to use fixed length strings. Dynamic strings are actually pointers to a
string descriptor and saving a type that contains dynamic strings will save the 4 byte
pointer value, rather than the actual string data, resulting in data loss.
Line 12 creates a variable of the type, Employee. The type definition is a template
and cannot be used until you create an instance of the type by creating a variable of the
type. Lines 15 through 20 initialize the type variable with some data using the a With-End
With block.
Line 23 prints a header row to the console that indicates the field name data. The
Tb function is used to align data names to the appropriate column. Line 24 uses the
String function to print a dashed line, just to offset the header row from the data row.
Lines 26 through 28 prints the type data. Rtrim is used on the fixed length string
elements to trim off any unused trailing spaces. The Tab function is again used to align
the data to the appropriate columns. The program is then ended in the usual way.
When you run the program you should the following output.
FirstNameLastNameEmpIDDept
SusanJones100124
Output 10.1: Output of type.bas
As you can see from the program, using a type definition is a perfect way to group
related data into a single data structure. Not only is it a compact way to describe data in
your program, but by grouping related data into a single object, you can manipulate that
data as a single entity, rather than as a bunch of unrelated variables. This reduces the
chances that errors will creep into your program by trying to manage large a set of
individual variables.
Types Within Types
In addition to the intrinsic data types, type fields can also be based on a type
definition. Why would you want to do this? One reason is data abstraction. The more
general your data structures, the more you can reuse the code in other parts of your
program. The less code you have to write, the less chance of errors finding their way into
your program. Using the Employee example, suppose for a moment that you needed to
track more dept information than just the department id. You might need to keep track of
the department manager, the location of the department, such as the floor or the
building, or the main telephone number of the department. By putting this information
into a separate type definition, you could this information by itself, or as part of another
type definition such as the Employee type. By generalizing your data structures, your
program will be smaller, and much more robust.
Using a type within a type is the same as using on of the intrinsic data types. The
following code snippets illustrates an expanded department type and an updated
employee type.
TypeDepartmentType
119