Difference between revisions of "Records"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Create a Record Structure)
Line 20: Line 20:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
This will need to go within your program, but NOT in any method or subroutine. You can now create an array of this:
+
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:
  
 
<syntaxhighlight lang=c#>
 
<syntaxhighlight lang=c#>

Revision as of 10:51, 20 December 2018

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. :

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;