FANDOM


USER DEFINED TYPES

If the current set of datatypes is inadequate for your needs, you can can create your own data types using user-defined-type. User defined types are useful for storing data using logical fields rather than the unfriendly list of subscripts used by arrays.

To create a user defined type, you must first declare it at the top of your program. To do so, you would give your type a name and a list of fields it contains:

TYPE MyType
 Fieldname1
 Fieldname2
 Fieldname3
ENDTYPE

The above code creates a type called MyType with three fields contained within it. As the fields have no declaration, they are assumed to be integers. The same code could also be truncated to a single line like so:

TYPE MyType Fieldname1 Fieldname2 Fieldname3 ENDTYPE

To use your type, you simply create a variable and declare it with your new type. To declare a variable as a specific type, you would use the AS statement:

MyVariable AS MyType

You can then assign data to your variable as normal, with the added bonus of the fields you have given your variable like so:

MyVariable.Fieldname1 = 41
MyVariable.Fieldname2 = 42
MyVariable.Fieldname3 = 43

At the moment, the type is assuming our fields are integers. We may wish to declare our fields as a real number, string or other datatype. We can do so using the same AS statement within the type definition. So the following code makes more sense we shall give our type and fields sensible names:

TYPE AccountEntryType
 Number AS INTEGER
 Name AS STRING
 Amount AS FLOAT
ENDTYPE

You can use a type like any other, so creating and using an array of the above is simply a case of declaring the array with your new type:

DIM Accounts(100) AS AccountEntryType
Accounts(1).Number=12345
Accounts(1).Name="Lee"
Accounts(1).Amount=0.42

As you will eventually discover you can have types within types for more complex data structures so we can imagine one of the fields contains more than one value. We would define two user defined types, and then use one of them in the declaration of one of the fields of the section user defined type, as follows:

TYPE AmountsType
 CurrentBalance AS FLOAT
 SavingsBalance AS FLOAT
 CreditCardBalance AS FLOAT
ENDTYPE

TYPE AccountEntryType
 Number AS INTEGER
 Name AS STRING
 Amount AS AmountsType
ENDTYPE

DIM Accounts(100) AS AccountEntryType
Accounts(1).Number=12345
Accounts(1).Name="Lee"
Accounts(1).Amount.CurrentBalance=0.42
Accounts(1).Amount.SavingsBalance=100.0
Accounts(1).Amount.CreditCardBalance=-5000.0

As you can see, user defined types are not only powerful, they make the readability of your programs far easier. Using named fields instead of a subscript value within an array, you can save yourself many hours all for the sake of an incorrect subscript value throwing out your program results.