This article originally
appeared in the Builder.com Visual Basic
e-newsletter. Click
here to subscribe automatically.
A user defined type, or UDT, is a VB technique for defining
a data type that exactly meets the needs of your program. A UDT can contain two
or more individual data items that can be of different types, such as String
and Integer. A UDT can even contain other UDTs and
arrays. You can also create arrays of a UDT.
To define a UDT, use the Type…End
Type statement, which must appear in the declarations section of a code
module. Within the statement, you define the individual items, or members, that
the UDT will contain.
Here’s an example of a UDT you might create for keeping
track of employee data:
Public Type Employee
FirstNameAs String
LastName As String
DateOfHire As Date
Salary As Currency
EmployeeNumber As Integer
End Type
Once you define the type, you can create instances of it
just like any other data type, like so:
Dim OneEmployee As Employee
Dim AllEmployees(500) As Employee
To access the members of a UDT, you use the Name.Member
notation. Here are some examples:
OneEmployee.FirstName = “Jack”
OneEmployee.LastName = “Sprat”
AllEmployees(1).FirstName = “Maria”
AllEmployees(1).LastName = “Sanchez”
Nesting UDTs can be useful in some
situations. Here’s an example:
Public Type Person
FirstNameAs String
LastName As String
End Type
Public Type Employee
Name As Person
DateOfHire As Date
Salary As Currency
EmployeeNumber As Integer
End Type
When UDTs are nested, you use the
same Name.Member
notation but with an extra level, like this:
Dim OneEmployeeAs Employee
OneEmployee.Name.FirstName = “Jack”
You can also use UDTs for
arguments to functions and procedures and as the return type for functions.
They can also be helpful when storing data on disk because VB’s
Random file type is specifically designed to work with UDTs.
All in all, UDTs are a tool that
every VB programmer should know about.
Peter Aitken has been programming with Visual Basic since Version
1.0. He has written numerous books and magazine articles on Visual Basic and
other computer and programming topics.