Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
You begin a structure declaration with the Structure Statement, and you end it with the End Structure statement. Between these two statements you must declare at least one element. The elements can be of any data type, but at least one must be either a nonshared variable or a nonshared, noncustom event.
You cannot initialize any of the structure elements in the structure declaration. When you declare a variable to be of a structure type, you assign values to the elements by accessing them through the variable.
For a discussion of the differences between structures and classes, see Structures and Classes.
For demonstration purposes, consider a situation where you want to keep track of an employee's name, telephone extension, and salary. A structure allows you to do this in a single variable.
To declare a structure
Create the beginning and ending statements for the structure.
You can specify the access level of a structure using the Public, Protected, Friend, or Private keyword, or you can let it default to
Public.Private Structure employee End StructureAdd elements to the body of the structure.
A structure must have at least one element. You must declare every element and specify an access level for it. If you use the Dim Statement without any keywords, the accessibility defaults to
Public.Private Structure employee Public givenName As String Public familyName As String Public phoneExtension As Long Private salary As Decimal Public Sub giveRaise(raise As Double) salary *= raise End Sub Public Event salaryReviewTime() ' Method to raise the event Public Sub TriggerSalaryReview() RaiseEvent salaryReviewTime() End Sub End StructureThe
salaryfield in the preceding example isPrivate, which means it is inaccessible outside the structure, even from the containing class. However, thegiveRaiseprocedure isPublic, so it can be called from outside the structure. Similarly, you can raise thesalaryReviewTimeevent indirectly by calling a method within the structure that raises it. For example:Public Sub TriggerSalaryReview() RaiseEvent salaryReviewTime() End SubThis allows you to control how and when the event is raised while keeping the event inaccessible directly from outside the structure.
In addition to variables,
Subprocedures, and events, you can also define constants,Functionprocedures, and properties in a structure. You can designate at most one property as the default property, provided it takes at least one argument. You can handle an event with a SharedSubprocedure. For more information, see How to: Declare and Call a Default Property in Visual Basic.