User Defined Types

Custom types.

User-Defined Types are special kinds of variables which can be created by the programmer. A User-Defined Type (UDT) is really just a container that contains a bunch of other variables, like an array, but unlike arrays, UDTs can hold different variable types (whereas arrays always hold many variables of the same type). In fact, UDTs can even have procedures inside of them!

The different variables and/or procedures stored inside a UDT are called "members", or more generally, items. Members can be variables of just about any type, including numerical types, strings, pointers, enums, and even arrays. Variables are created in UDTs much the same way variables are created normally, except that the Dim keyword is optional. UDT members are accessed via the . operator, so for example if you created a variable called someVar in a UDT you would access it with the name of the UDT variable followed by ".someVar". Here is an example:

'Define a UDT called myType, with an Integer member named someVar
Type myType
  As Integer someVar
End Type

'Create a variable of that type
Dim myUDT As myType

'Set the member someVar to 23, then display its contents on the screen
myUDT.someVar = 23
Print myUDT.someVar

Notice that the Type...End Type does not actually create a variable of that type, it only defines what variables of that type contain. You must create a variable of that type to actually use it!

UDT Pointers
UDT Pointers are, as the name implies, pointers to UDTs. They are created like regular pointers, but there is a special way to use them. To access the member of a UDT pointed to by a pointer, you use the -> operator. For example, if myUDTPtr is a pointer to a UDT which has a member someVar, you would access the member as myUDTPtr->someVar, which is a much cleaner shorthand for the equally valid (*myUDTPtr).someVar.

Type rect
    x As Integer
    y As Integer
End Type

Dim r As rect
Dim rp As rect Pointer = @r

rp->x = 4
rp->y = 2

Print "x = " & rp->x & ", y = " & rp->y

UDT Instantiation
When creating an object of a UDT:
- only non-static data members induce a specific memory allocation to each object instance,
- static data members are allocated only once for the UDT and are therefore common to all object instances,
- procedure members are also defined only once for the UDT and their code is not duplicated for each object instance (and this, even for the non-static procedure members).

That is why a static variable declared inside any procedure member is allocated only once for the UDT.
Therefore this static variable is indeed permanent but shared by all UDT instances executing the code (it is not an instance-specific variable).

See also:

Back to Programmer's Guide
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki phatcode