Records

From TRCCompSci - AQA Computer Science
Revision as of 11:52, 20 December 2018 by Admin (talk | contribs) (Using your struct)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Issues with Arrays

An array can only be of a single data type, for example and array of int or an array of string. This is because arrays are a data structure, they are an extension of the data types and are based upon the data type chosen.

However, you can essentially define your own type (Record) and then create an array of that instead.

Create a Record Structure

The command struct can be used to declare a new structure:

        struct Book
        {
            int ID;
            string Title;
            string Author;
            double RetailPrice;
            string Description;
            int Edition;
            bool Fiction;
        }

This will need to go within your program, but NOT in any method or subroutine.

Using your struct

You can now create an array of this:

        Book[] collection = new Book[100];

You can then easily add a book to this structure by maintaining a variable called bookCount, which is incremented every time a book is added. Best practice is to create a temporary book and set the values, then to store this in the appropriate collections element:

Book temp = new Book;
temp.ID = 999;
temp.Title = "Black Mirror";
temp.Author = "Charlie Brooker";
temp.RetailPrice = 9.99;
temp.Description = "An view of the future";
temp.Edition = 1;
temp.Fiction = true;
collection[bookCount] = temp;