JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Structures

Traditionally, structures were used to let you create your own complex data types. For example, if you wanted to store both an employee's ID value (an integer) and a employee's name (a string) in one variable, you could create a new structure named, say, Employee, like this:

Public Structure Employee
    Public Name As String
    Public ID As Integer
End Structure

This creates a new data type. Now you can declare a variable of this new type, and access the data fields in it, like this:

Dim employee As Employee
employee.Name = "Cary Grant"
employee.ID = 101

Now, however, structures are much like classes and can support events, methods, and properties as well as fields. To create a structure, you use the Structure statement at the module or class level:

[ <attrlist> ] [{ Public | Protected | Friend |
Protected Friend | Private }] Structure name
   [ variabledeclarations ]
   [ proceduredeclarations ]
End Structure

Here are the parts of this statement:

  • attrlist—Optional. List of attributes for this structure. Separate multiple attributes by commas.

  • Public—Optional. Structures declared Public have public access; there are no restrictions on the accessibility of public structures.

  • Protected—Optional. Structures declared Protected have protected access, which means they are accessible only from within their own class or from a derived class.

  • Friend—Optional. Structures declared Friend have friend access, which means they are accessible from within the program that contains their declaration and from anywhere else in the same assembly.

  • Protected Friend—Optional. Structures declared Protected Friend have both protected and friend access. They can be used by code in the same assembly, as well as by code in derived classes.

  • Private—Optional. Structures declared Private have private access, which means they are accessible only within their declaration context.

  • name—Required. Name of the structure.

  • variabledeclarations—Optional. One or more Dim, Friend, Private, or Public statements declaring variables that are the data members of the structure. Note that these declarations follow the same rules as they do outside of a structure.

  • proceduredeclarations—Optional. One or more declarations of Function, Property, or Sub procedures that are the method members of the structure. Note that these declarations follow the same rules as they do outside of a structure.

Each attribute in the attrlist part has the following syntax:

<attrname [({ attrargs | attrinit })]> Attrlist

Here are the parts of attrlist:

  • attrname—Required. Name of the attribute.

  • attrargs—Optional. List of positional arguments for this attribute. Separate multiple arguments by commas.

  • attrinit—Optional. List of field or property initializers for this attribute. Separate multiple initializers by commas.

Note that you must declare every data member of a structure. This means every statement in the variabledeclarations part must contain Dim, Friend, Private, or Public. If Option Strict is On, you also must include the As clause in every statement. Members declared with Dim default to public access, and members declared without the As clause default to the Object data type.

Note 

You cannot initialize the value of any data member of a structure as part of its declaration. You must either initialize a data member by means of a parameterized constructor on the structure, or assign a value to the member after you have created an instance of the structure.

You can assign one structure variable to another of the same type, and all the members will be copied as well. However, to compare structures, you must compare each member individually currently in Visual Basic, although that may change in the future.

As mentioned, structures support many of the same features as classes. However, as discussed in the In Depth section of this chapter, there are a number of features of classes that are not supported in structures—see the In Depth section for more information.

Also, structures are value types rather than reference types. This means that when you copy a structure, it's copied by value, not reference. And in Visual Basic, it also means that you can't convert from structures to classes, such as the Object class. That's often important. For example, in the ComboBoxData example from Chapter 7 that we took a look at in the In Depth section of this chapter (see "An OOP Example"), I created an array of objects named Objects and used a combo box's AddRange method to add the whole array to the combo box at once:

ComboBox1.Items.AddRange(Objects)

However, AddRange takes an array of type Object by default, and an array of structures can't be converted to an array of type Object. Instead, I'll add each structure to the combo box one at a time. The rest of the code is the same, except that DataItem is now a structure instead of a class, and even supports constructors, methods, and so on, as you can see in the Structures example on the CD-ROM:

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
        Dim Objects(20) As DataItem
        ComboBox1.BeginUpdate()
        Dim intLoopIndex As Integer
        For intLoopIndex = 0 To 20
            Objects(intLoopIndex) = New DataItem("Item " & _
                intLoopIndex, CSng(intLoopIndex))
            ComboBox1.Items.Add(Objects(intLoopIndex))
        Next
        ComboBox1.EndUpdate()
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As _
        System.Object, ByVal e As System.EventArgs) Handles _
        ComboBox1.SelectedIndexChanged
        MsgBox("The data for the item you selected is: " & _
            CType(ComboBox1.SelectedItem, DataItem).GetData())
    End Sub
End Class

Public Structure DataItem
    Private Data As Single
    Private Name As String
    Public Sub New(ByVal NameArgument As String, ByVal Value As Single)
        Name = NameArgument
        Data = Value
    End Sub

    Overrides Function ToString() As String
        Return CStr(Name)
    End Function

    Public Function GetData() As Single
        Return Data
    End Function
End Structure

The Structures example works just as the ComboBoxData example did (which you can see in Chapter 7, Figure 7.15), except that now the data is stored in structures.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor