3.2.6 - Records and fields (VB.NET)
Group related fields into a record and use it in a VB.NET solution. Native code answers are written without Run; the optional Python demonstration uses a dictionary to explore named fields.
Grouping related fields
A record groups fields describing one entity, and each field has its own name and suitable type.
Record
A data structure containing related named fields, which may have different data types.
One car has a make, model, registration, price and number of doors. These belong together, but the registration is text, the price may be fractional and the door count is an integer. A homogeneous numeric array would not naturally represent all these roles.
VB.NET can represent a record using a Structure. Put this type declaration inside the program's module, outside Sub Main:
Structure Car
Public make As String
Public model As String
Public registration As String
Public price As Double
Public numberOfDoors As Integer
End Structure
Car defines the field layout; it is not yet a particular car. Public allows the fields to be accessed by code using the structure. Dim firstCar As Car creates a variable of that type. Dim secondCar As Car creates another, with the same field layout but its own values. A record's field name identifies a role; an array's index identifies an element position.
Use strings for registrations even when they include digits: they are identifiers, not quantities to calculate. Choose Double for a price here, and Integer for a door count. Fields with the same type still need distinct names because make and model mean different things.
Using records in a solution
Dot notation accesses a particular record's named field for reading or assignment.
Place these statements inside Main, using the Car declaration above:
Dim firstCar As Car
firstCar.make = "Aster"
firstCar.model = "City"
firstCar.registration = "AB12 CDE"
firstCar.price = 7500.5
firstCar.numberOfDoors = 5
If firstCar.numberOfDoors = 5 Then
Console.WriteLine(firstCar.make & " " & firstCar.model)
End If
firstCar.price = firstCar.price - 500
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account