Structures


Arrays require that every element in the array be of the same type.  This is adequate when dealing with customer names or student scores.  However, there is usually more than one piece of data about a customer or a student.  If all of the data is of the same type, then a multidimensional array can be used.  If some of the data is of a different type, then parallel arrays can be used; however, it is sometimes cumbersome to maintain separate data structures, and it is very easy to forget to update one or more of the parallel arrays.

In grouping items describing an object, a structure may be a more logical description of the data and may be conceptually easier to handle than other data structures.

When the structure variable name and the element names reflect the meaning of the data, programs are both easier to read and write.  Even when all the components are of the same type, a structure is sometimes the best choice of data structures if the components are related.

By using arrays of structures, data can be represented in a more meaningful manner.


Declaring a Structure

A structure can be declared by using the Structure keyword in the General section of a module:

          <modifier> Structure <struct_name>
                   <varmodifier> elementName [(subscripts)] As type
                   [<varmodifier> elementName [(subscripts)] As type]
                   . . . 
          End Structure  

In this syntax, 

The Structure statement can only be used at the module or class level.


Referencing Structure Elements

To access the elements of a structure, the name of the structure must be specified, followed by a period, followed by the name of the element. In many languages, this is called the field selector or member selector. The field selector is treated and used as any other declared variable would be. The field selector acts as the variable name for each field. It must be complete. 

        VarName.ElementName

Where

              Private Structure PersonStructure 
                     ' Dim (Public) members, accessible throughout declaration region.
                     Dim Name As String
                     Dim Gender As String
                     Dim SSN As String
                     Dim MaritalStatus As String
                     Dim Degree( ) As String
              End Structure 'PersonStructure 

 

              Dim Student as PersonStructure 

Name, Gender, SSN, MaritalStatus, and Degree are the element names within the structure PersonStructure.  These element names will be used to access the different components of the variable Student declared to be of type PersonStructure.

             Student.Name = "Wallace Cleaver"

 

Arrays declared as structure members cannot be declared with an initial size.

Part of a structure cannot be accessed outside the structure. Although Student.Name is declared as a String, Name is not an individual variable and cannot be referenced directly in the program as Student.Name can.

Student.Name -- accesses the string that holds the name 
Student.Gender -- accesses the gender
Student.SSN -- accesses the string that holds the social security number
Student.MaritalStatus -- accesses the marital status
Student.Degree -- accesses the degree(s) held

 

Student.Degree is an array, so it's size must be specified with a ReDim statement and an index will have to be specified to access individual elements:

ReDim Student.Degree(3)
Student.Degree(0) = "BA"
lblOutput.Text = Student.Degree(0)

 

 


Another Example

 

If each item in an inventory list is described by part number, description, cost, and quantity on hand, then a structure would be an ideal choice to describe it:

 

               Private Structure  PartStructure 
                      Dim partNum As String
                      Dim description As String
                      Dim cost as Decimal
                      Dim quantity as Integer
               End Structure  ' PartStructure 

               Dim part as PartStructure 

The following statements could be applied to part:


Hierarchical Structures

Hierarchical structures are structures that contain other structures as their components.

Private Structure dateStructure 
      Dim month as Integer      ' assume 1-12
      Dim day as Integer           ' assume 1-31
      Dim year as Integer
End Structure 'dateStructure 

Private Structure statisticsStructure 
     Dim failRate as Single
     Dim lastServiced as dateStructure    '*******
     Dim downDays as Integer
End Structure ' statisticsStructure 

Private Structure machineStructure 
    
Dim ID as Integer
    
Dim description as String
    
Dim maintHistory as statisticsStructure      '*******
    
Dim purchaseDate as dateStructure            '*******
    
Dim cost as Decimal
    
Dim depreciatedValue as Decimal
End
Structure 'machineStructure 


Dim machine as
machineStructure 

To access a hierarchical structure such as this one, build the accessing expression for the elements of the embedded structures from left to right, beginning with the structure variable name.  

machine.maintHistory.downdays
machine.purchaseDate
machine.purchaseDate.month
machine.purchaseDate.year
machine.maintHistory.lastServiced.year

The figure below is a graphical representation of machine with values.  Look carefully at how each component is accessed.


Arrays of Structures

Generally, more than a single structure is needed.  In such a case an array of structures can be used.

Private Structure StudentStructure 
     Dim Name as String
     Dim Course as String
     Dim GPA as Single
     Dim Major ( ) as String
End Structure 'StudentStructure 

Dim studentRoll (50) as StudentStructure 

An element of studentRoll is selected by a subscript: studentRoll(3) is the fourth element of studentRoll.  Each element of studentRoll is a structure of type StudentType.  In order to access the grade point average of the fourth student in studentRoll we type 

studentRoll(3).GPA

 

To access the first major of the second student, we type

ReDim  studentRoll(1).Major(2)
studentRoll(1).Major(0) = "CIS"

 You could access


Passing Structures to Procedures

You can return structures from functions, and you can pass a structure variable to a procedure as one of the arguments.  If MySystem is declared as 

Private Structure SystemInfoStructure 
     Dim CPU as String
     Dim Memory as Integer
     Dim Cost as Decimal
     Dim PurchaseDate as Date
End Structure 'SystemInfoStructure 

Dim MySystem As SystemInfoStructure
Call FillSystem ( MySystem )

...then it can be passed as a parameter to and/or from a procedure.  In the example below, values for the elements of SomeSystem (of type SystemInfoStructure ) are read from the form.

Sub FillSystem (ByRef SomeSystem As SystemInfoStructure )
      SomeSystem.CPU = lstCPU.Text
      SomeSystem.Memory = txtMemory.Text
      SomeSystem.Cost = txtCost.Text
      SomeSystem.PurchaseDate = Today    ' Could also use Now
End Sub

Structures are usually passed by reference, so the procedure can modify the argument and return it to the calling procedure, as illustrated in the previous example. 


The With Statement

The With statement can be used as a convenient method of abbreviating a field selector:

        Sub FillSystem (ByRef SomeSystem As SystemInfoStructure )
   
          With SomeSystem
                  .CPU = lstCPU.Text
                  .Memory = txtMemory.Text
                  .Cost = txtCost.Text
                  .PurchaseDate = Today
              End With
   
     End Sub

You can nest With statements if hierarchical structures are used.

                With machine
                     .ID = 5719
                     .description = "Drill Press"
                      With .maintHistory 
                             .failRate = 0.02
                             With .lastServiced
                                  .month = 1
                                  .day = 25
                                  .year = 1996
                             End With
                             .downDays = 4
                      End With
                      With .purchaseDate
                             .month = 3
                             .day = 21
                             .year = 1995
                      End With
                      .cost = 8000.00
                     .depreciatedValue = 5500.00
                End With


Structures in VB.Net can be much more complex, but a more simple version -- a simple grouping of attributes -- has been presented to provide a transition to the concept of classes and objects.


See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmStructure.asp