Structures

advertisement
Structures
A structure is a convenient way to organize related variables. A structure is defined like this:
Private Structure Student
Dim FirstName As String
Dim LastName As String
Dim Age As Byte
Dim LikesSimpsons As Boolean
End Structure
The structure definition includes a scope declaration (Private or Public, usually), the word “Structure”,
and then the name of the structure (“Student” in this case). It ends with and “End Structure” line. In
between are variable declarations. These variables become the member variables of the structure. The
structure itself becomes, in effect, a new data type. After defining the structure above, I can now
declare variables to be of type Student:
Dim newstudent As Student
See the code in the Structures sample project for an example of how a structure is declared and used.
Don’t get confused between the definition of the structure (Private Structure Student, etc.) and the
actual variables of the structure’s type (newstudent, for example). The variables, like newstudent, are
instances of the structure. You can have as many variables of type Student as you want; each will have
its own set of data. These variables are all instances of the Student structure.
Try adding some additional students to the Structures project, and get comfortable assigning values to
the member variables of each student variable.
Eventually, we will learn about Classes, which are basically Structures on steroids. But sometimes, a
structure is all you need. They’re also widely used in existing VB code, so you should know about them if
you ever inherit somebody else’s program.
Download