Visual Basic 2010 (Console) Guide
Records (Structure)
The built-in data types discussed on previous pages are good enough for most of the situations where we need to store information. It becomes a bit more difficult if we need to store more than one piece of information about a thing. For example, if we were storing details of a book in a data structure, we would need to be able to store things like the following,
- Title
- Author
- ISBN
- Publisher
- Year Published
- Price
The first 4 items in the list are strings (ISBN can end in an X). The Year is an integer and the price a double or decimal. A single data type just won't do here.
Most programming languages include provision for a user-defined type. In Pascal, this type is called a record - this term is important as it might be used in exam questions. However, in Visual Basic, this is called a Structure. Structures can do much more than is shown in this page - but for now this is enough.
Structure Sample
Structure TBook
Dim title As String
Dim author As String
Dim isbn As String
Dim publisher As String
Dim year As Integer
Dim price As Double
End Structure
Sub Main()
Dim book1 As New TBook()
book1.title = "My Booky Wook"
book1.author = "Russell Brand"
book1.isbn = "9780340936153"
book1.publisher = "Hodder & Stoughton"
book1.year = 2007
book1.price = 18.99
Console.WriteLine("{0} by {1}, price £{2}", book1.title, book1.author, book1.price)
Console.ReadLine()
End Sub
Study the example carefully. The structure is declared using the keyword, structure. The structure itself consists of a series of variable declarations. We call these fields.
The structure declaration was written outside of the main program. Within the program, look carefully at how an instance of this structure was created and how the fields were set and read at a later time.
Structures are much more powerful than this example shows. They can have methods, including a constructor method to make it easier to initialize instances of the structure. For now though, this is all we need.